473,382 Members | 1,441 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

Best approach to validating "set" property ..

Hello!

I have a class that needs to validate the input value, when a programmer
changes a specific property on a class. The input should only accept the
following pattern [a-zA-Z0-9]{1,n} (alpha-numeric with atleast one entry).

I'm a little resistant to implementing a regular expression validation,
because of the overhead involved (not because I can't :-). Obviously, it's
possible to implement the pattern validation using regular string ops ..

What should I choose? I imagine the access frequency is rather low, but I
don't want to go the wrong direction - also in terms of future API
development.

// Class definition omitted for brevity..

/// <summary>
/// Gets or sets the Area name. The Area name must be a fully
/// qualified ASP.NET control id in the form of [a-zA-Z0-9].
/// </summary>
public string AreaName
{
get { return this.areaName; }
set
{
// include validation here ..
// RegEx or string-ops?
this.areaName = value;
}
}

Thanks in advance!

--
venlig hilsen / with regards
anders borum
--
Nov 15 '05 #1
9 3481
Anders Borum <na@na.na> wrote:
I have a class that needs to validate the input value, when a programmer
changes a specific property on a class. The input should only accept the
following pattern [a-zA-Z0-9]{1,n} (alpha-numeric with atleast one entry).

I'm a little resistant to implementing a regular expression validation,
because of the overhead involved (not because I can't :-). Obviously, it's
possible to implement the pattern validation using regular string ops ..

What should I choose? I imagine the access frequency is rather low, but I
don't want to go the wrong direction - also in terms of future API
development.


If the regular expression is simple to read, but the "hand-crafted"
code wouldn't be very simple, go with the regular expression until you
have evidence that it's being too slow. If you end up with a monster
regular expression that can easily be expressed in actual code, leave
it as code.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
Hello Jon

(and thanks for the quick reply)

I was thinking of the RegEx approach because of the clean code (and
incredible flexibility in terms of changes the RegEx pattern), compared to
the more verbose (and harder to read) string ops.

As I said, the property is unlikely to be used extensively, so the RegEx is
probably the best approach at the moment. Thanks for your thoughts.

--
venlig hilsen / with regards
anders borum
--
Nov 15 '05 #3

"Anders Borum" <na@na.na> wrote in message
news:O3**************@TK2MSFTNGP09.phx.gbl...
Hello Jon

(and thanks for the quick reply)

I was thinking of the RegEx approach because of the clean code (and
incredible flexibility in terms of changes the RegEx pattern), compared to
the more verbose (and harder to read) string ops.

This one is easy.

private static bool IsAlphaNumeric(string s)
{
foreach (char c in s)
{
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' &&
c <= 'Z')))
{
return false;
}
}
return true;
}

And much faster than a regex, which can be important when you are desiging a
library and you don't now know often each method will be executed.

David
Nov 15 '05 #4
Hello David

Actually, as I indicated the property is unlikely to be used extensively,
but I'm naturally always on the lookout for the best approach.

If you examine the following RegEx, you'll see that the length needs to be
one or more, and always start with one of the following chars "a-z_", then
followed by zero or more alpha-numeric chars (including underscore).

if (Regex.IsMatch(value, @"^[a-z_]\w*$", RegexOptions.IgnoreCase) == false)

How about that one? ;-)

--
venlig hilsen / with regards
anders borum
--
Nov 15 '05 #5
Hello John

In trying to develop strong coding skills (and patterns), I'm asking for a
constructive discussion on the following two code examples with equal
functionality, but different implementation.

If you were a programmer looking over the API, would you find it difficult
to understand the second example? I'm not sure if the output IL would yield
a big performance difference (comments please).

Which would you choose?

/// <summary>
/// Determines if the Area has any child Areas. The disconnected state
/// does not reflect changes to the persisted Area (e.g. if other users have
/// changed the child Area after the current object was initialized).
/// </summary>
public bool HasAreas
{
get
{
bool retVal;

// Collection not cached (initialized from db)
if (areas == null)
{
// Use the Area reference count from db
retVal = (areaRefs > 0);
}
else
{
// Use cached collection (previously initialized from db)
retVal = (areas.Count > 0);
}

return retVal;
}
}

In contrast to this ..

/// <summary>
/// Determines if the Area has any child Areas. The disconnected state
/// does not reflect changes to the persisted Area (e.g. if other users have
/// changed the child Area after the current object was initialized).
/// </summary>
public bool HasAreas
{
get { return (this.areas == null) ? (this.areaRefs > 0) :
(this.areas.Count > 0); }
}

Again - thank you!

--
venlig hilsen / with regards
anders borum
--
Nov 15 '05 #6

"Anders Borum" <na@na.na> wrote in message
news:OH**************@TK2MSFTNGP09.phx.gbl...
Hello David

Actually, as I indicated the property is unlikely to be used extensively,
but I'm naturally always on the lookout for the best approach.

If you examine the following RegEx, you'll see that the length needs to be
one or more, and always start with one of the following chars "a-z_", then
followed by zero or more alpha-numeric chars (including underscore).

if (Regex.IsMatch(value, @"^[a-z_]\w*$", RegexOptions.IgnoreCase) == false)


private static bool IsAlphaNumeric(string s)
{

if (s.Length == 0)
{
return false;
}
char c = s[0];
if (!((c >= 'a' && c <= 'z') || c = '_'))
{
return false;
}
for (int i = 1; i < s.Length; i++)
{
c = s[i];
if (!((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
c == '_'))
{
return false;
}
}
return true;
}

But notice how this program "looks" like the regex. A Regex is just a
recipe for a program. In fact a regex IS a program. You just have to
decide whether to implement it in "regex" or in C#.

For trivial programs, stick with C#. It's faster and you need a compelling
reason to mix programming languages in a project. The more complicated the
pattern, the better of you are with a Regex. But on the other hand, regex's
lack any mechanism for encapsulation, so as the regex gets even more
complicated, hand coding can be simpler.

David
Nov 15 '05 #7
Anders Borum <na@na.na> wrote:
In trying to develop strong coding skills (and patterns), I'm asking for a
constructive discussion on the following two code examples with equal
functionality, but different implementation.

If you were a programmer looking over the API, would you find it difficult
to understand the second example? I'm not sure if the output IL would yield
a big performance difference (comments please).

Which would you choose?


I would either choose the latter, or the following:

// Is the collection cached (previously initialized from db)?
bool cached = (areas!=null);

return ( (cached && areas.Count > 0) || (!cached && areaRefs > 0) );

Ultimately either is pretty readable - although I'd comment the second
version slightly more, I think.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #8
Hello Jon

Thanks for the effords so far. It's been quite interesting.
I would either choose the latter, or the following:

// Is the collection cached (previously initialized from db)?
bool cached = (areas!=null);

return ( (cached && areas.Count > 0) || (!cached && areaRefs > 0) );
Isn't the following code faster? You're making use of a variable, and I was
under the impression that the "? :" syntax is an highly optimized pattern?

public bool HasAreas
{
get { return (areas == null) ? (areaRefs > 0) : (areas.Count > 0); }
}
Ultimately either is pretty readable - although I'd comment the second
version slightly more, I think.


Yes, I'm a big fan of commenting source-code. You never know, when (or who)
you're going to review it.

--
venlig hilsen / with regards
anders borum
--
Nov 15 '05 #9
Anders Borum <na@na.na> wrote:
I would either choose the latter, or the following:

// Is the collection cached (previously initialized from db)?
bool cached = (areas!=null);

return ( (cached && areas.Count > 0) || (!cached && areaRefs > 0) );


Isn't the following code faster? You're making use of a variable, and I was
under the impression that the "? :" syntax is an highly optimized pattern?

public bool HasAreas
{
get { return (areas == null) ? (areaRefs > 0) : (areas.Count > 0); }
}


I would certainly hope that they'd be optimised to roughly the same
code, and I'd want to see *very* definite proof that the optimisation:

a) worked
b) was absolutely necessary

before sacrificing even a *jot* of readability.
Ultimately either is pretty readable - although I'd comment the second
version slightly more, I think.


Yes, I'm a big fan of commenting source-code. You never know, when (or who)
you're going to review it.


Indeed.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Dave_NH | last post by:
I would like my VB application to set some specific values in the "Result" code so that when we check the "Last Result" column in Scheduled Tasks we'll see that information. Suggestions?
10
by: Mart | last post by:
What class does everyone out there use if they want to store a set of values efficiently? In java I use a HashSet, but there is no equivalent in C#. Even worse, the lowest level interface to...
0
by: Dana Epp | last post by:
Anyone know how to set the "Disabled" imagelist in a C# Toolbar? Although the Microsoft's Toolbar ActiveX control in the mscomctl.ocx has such a property, there doesn't seem to be one for the C#...
0
by: Pierson C | last post by:
A quick easy one! I have a custom user control that has an ArrayList property. I create an instance of the user control, assign all of the properties, but when I add the control to the page, my...
6
by: Just Me | last post by:
What does "Set not supported at runtime" in the Task List mean? Thanks in advance for any info
0
by: Bobby Owens | last post by:
Hi, I'm current having a problem with the treeview control and multi threading. The treeview is on a form. A request is then sent to a server using IP for the data. The data arrives in an event...
1
by: Jake Barnes | last post by:
I can not figure out the meaning of this error: Error: " nsresult: "0x8057001e (NS_ERROR_XPC_JS_THREW_STRING)" location: "JS frame :: http://www.bluecasts.com/pdsIncludes/pdsAjax.js ::...
9
by: axs221 | last post by:
I am trying to move some of our large VBA Access front-end file into ActiveX DLL files. I created two DLL files so far, one was a module that contains code to integrate into the QuickBooks...
1
by: Bill Stillwell | last post by:
I am trying to set the "backcolor" property in fields in a form. It sets okay using a macro (setvalue). But when I close the form, the property settings revert back to what they were before I...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.