473,769 Members | 2,062 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3499
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.co m>
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******** ******@TK2MSFTN GP09.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.Ig noreCase) == 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.Cou nt > 0); }
}

Again - thank you!

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

"Anders Borum" <na@na.na> wrote in message
news:OH******** ******@TK2MSFTN GP09.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.Ig noreCase) == 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.co m>
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.co m>
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
410
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
17216
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 define the Add, Contains and Remove methods is an IList, and we all should know that a set isn't a list. ICollection only defines Count and CopyTo, which isn't useful at all. So even if I want to write my own Set implementation, what interface...
0
1238
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# version. Anyone know a work around for this? --- Regards, Dana M. Epp http://silverstr.ufies.org/blog/]
0
2494
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 ArrayList variable has gone out of scope (all int and string properties still exist). It must be where an ArrayList is treated like an Object, but there are shortcuts in place for strings and ints....
6
1789
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
1322
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 on a different thread. I have used delegates to allow me to add to the treeview and it all works fine. I cant however seem to set the "SelectedNode" property or the treeview. I have tried directly and also using a delegate. I all cases, the UI...
1
7176
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 :: submitAnyForm :: line 635" data: no] Source File: http://www.bluecasts.com/pdsIncludes/pdsAjax.js Line: 635
9
3102
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 accounting software. Another has general utilities. I tried referencing the utilities dll, and it shows up in the object explorer. I instantiated an instance of the class and now it shows up all okay in the Intellisense. Whenever I try to run a simple...
1
3210
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 closed the form. So when I reopen the form, the settings are not changed. If I manually change the settings while not in Design mode (using the "fill with" icon), the settings hold. If I change the settings while in Design mode, the settings do not...
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10215
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9996
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9865
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5307
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3964
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.