I am currently doing a project for school, and to get full marks you must;
More able candidates should use validation within the field Set method/Property of a class and throw back error messages where relevant. It is expected that a validation process calls methods from a static class.
Could someone please explain what the exam board mean by this?
Also,
More able candidates should be encouraged to make good use of try catch, get/set, and the use of specific or custom exceptions.
I've been doing validation like this:
if (isValidString(txtUsername.Text, "^[a-zA-Z0-9]*$") && (txtPassword.Text.Length > 5))
Does that mean I need to change something?
EDIT:
So, if I put my validation in the set method, will that tick this off?
It is expected that a validation process calls methods from a static class.
or is that something else?
More able candidates should use validation within the field Set method/Property of a class and throw back error messages where relevant. It is expected that a validation process calls methods from a static class.
I won't give you a code sample just so you figure out by yourself, however, a property (like public string Name { get; set: }) can have logic if you use a backing field.
For example:
public class Student
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
}
What they are asking you is to validate whatever is assigned to the property set method, instead of validating the input and then assigning it to the property.
More able candidates should be encouraged to make good use of try catch, get/set, and the use of specific or custom exceptions.
This overlaps somewhat with what I showed above. However, they are also asking you to throw specific/custom exceptions rather than general ones.
A basic example:
public void AssignName(string name)
{
if (name == null)
{
//WRONG!!!
// Exception is the base class, this doesn't provide you anything meaningful
throw new Exception("name is null!!!);
//Correct:
// ArgumentNullException tells you that a null value was passed when this isn't valid
throw new ArgumentNullException("name");
}
}
Related
I wrote the line of code below but the an error was highlighted, below:
get must declare a body it is not marked abstract, extern, or partial
I don't understand what the problem is? Why can't the set call a method without mucking up the get?
public string NoteColour { get; set { SetFontColour(value); } }
You have to supply an implementation for the get since the compiler only allowed auto-implemented properties if both the get and set have no implementation.
If you implement either of them, you have to give an implementation for the other one too.
I expect to have something like this:
public string NoteColour { get { return GetFontColor(); } set { SetFontColour(value); } }
The error suggests that you need to provide the body for your get method. So if you have created property by your own then you have to implement either both get and set or none.
public string NoteColour
{
get
{
return GetMethod();
}
set
{
SetFontColour(value);
}
}
If you don't write a body for get and set a macro is called which adds an hidden private field for your property in order to store the actual value. This is needed because a property has no memory associated with it and simply acts like a method working on your class object. It gives you the convince not to write explecit getter or setter methods like in old times.
If you want to do custom things (others than simply encapsulate a field), you have to declare both bodys since the macro does not know which field it should return.
Just for completeness:
private string noteColor = string.Empty;
public string NoteColour
{
get
{
return this.noteColor;
}
set
{
// add custom actions needed here
this.noteColor = value;
}
}
How bad of practice is this? I am currently being asked by my professor to do this which is against everything I have been told. Can anybody give me examples why you should not validate this way? (Using regular expressions in the get / set methods in a asp web page)
More Information:
Here is the code of what he wants us to do:
In the Property:
public String FName
{
get
{
return _fName;
}
set
{
if (validateName(value.ToString()))
_fName = value;
}
}
The method im calling:
public static bool validateName(String name)
{
bool isGood = true;
Regex regex = new Regex("^[A-Z]");
if (!regex.IsMatch(name))
isGood = false;
return isGood;
}
In general it's not good, as validating as is, presumes also a failure.
So the questions are:
How do you intend to handle faults during constructor code execution. ?
What if you get an exception in constructor? What the state of the object remains after that ?
That's why it's a bad practice in general. The good path to follow is to:
Construct object
Run validation
But these are guides, and you're free to brake them based on your convenience. So in deffence of your professor, should say, that he asked this:
Or to bring you to some thoughts
Or to teach you something
So follow his path and try to understand why he asked to write the code in that way.
It depends what you mean by validation, guard clauses are quite common practice in constructors e.g.
if(param1 == null)
throw new ArgumentNullException("param1");
It helps make sure that your object is in a consistent state for use later on (preventing you having to check at the time of use).
You can also use guard clauses on properties (what your case seems to be) and methods too, to ensure your object is always in a consistent state.
In reply to your update, I'd find that really annoying, for example:
var a = new yourObject();
a.FirstName = 123;
What my code doesn't know is that I've failed validation so I haven't changed the first name property at all!
Edit:
Your can also simplify your validation method:
public static bool validateName(String name)
{
Regex regex = new Regex("^[A-Z]");
return regex.IsMatch(name)
}
I agree with your instructor.
In general, you should validate a value in any place it is possible to set it prior to "accepting" it. The general rule is that whatever method that attempts to set the value should receive immediate feedback when it attempts to set it.
For your example, I would place the validator inside of the setter of your FName public property, and if your constructor also accepts a FName value, then simply call the FName setter within your constructor to fully encapsulate the behavior of the property, be it validation behavior or any other business rules that the property implements:
public class User
{
public User(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
if (!IsValid(value))
// throw / handle appropriately
else
_firstName = value;
}
}
}
Also: stay away from abbreviations! Do not use FName; use FirstName.
Purpose of a constructor is to assign values to the members of a type. By convention, validation is not responsibility of constructor.
Validation of any information is dependent on business of the application that you are building. If you are creating a modular application where every component is meant for a specific purpose, it is better to create a separate class or a set of classes (depending on size of the application) to perform all business validations. Such validations have to be invoked depending upon the validation rules imposed on a piece of data.
Hi I have this program that I am writing that uses the struct below. I keep getting a stackoverflow error and the exception is stops the program at the fist bracket in public string sessionID set...(where the ">>>" is).
public struct SessionStruct
{
public string sessionID
{
get
{
return sessionID;
}
set
>>> {
sessionID = value;
}
}
public DateTime time
{
get
{
return time;
}
set
{
time = value;
}
}
public string type
{
get
{
return type;
}
set
{
type = value;
}
}
};
Here is the code that sets the struct:
if (type == "11" || type == "9")
{
s.sessionID = attributeArray[0].ToString();
s.time = DateTime.Now;
if (type == "9")
s.type = attributeArray[4].ToString();
}
else
{
s.sessionID = null;
s.time = DateTime.Now;
s.type = null;
}
Thanks for the help in advance...
you're doing an infinite recursion in that setter. Think about it.
Create a private member of a different name to get/set.
private string sessionID;
public string SessionID
{
get
{
return sessionID;
}
set
{
sessionID = value;
}
}
The sessionId Property setter calls it self, causing an eternal recursion.
Your property is calling itself over and over again. The property really needs a backing store to store the data in, which is typically a private variable:
private string _sessionID;
public string sessionID
{
get
{
return _sessionID;
}
set
{
_sessionID = value;
}
}
Or let the compiler do it for you:
public string sessionID
{
// compiler will create a backing store for you
get; set;
}
That is because the set property calls itself (the name is the same).
You probably want to use an autoproperty
public string sessionID
{
get; set;
}
The problem is that you're recursing on the sessionID property.
This:
public string sessionID
{
get
{
return sessionID;
}
set
{
sessionID = value;
}
}
Will be compiled to something like this:
public string sessionID_get() { return sessionID_get(); }
public void sessionID_set(string value) { sessionID_set(value); }
Obviously this won't work!
You should be using a backing field:
private string _sessionID;
public string sessionID
{
get
{
return _sessionID;
}
set
{
_sessionID = value;
}
}
Alternatively, you can get the compiler to automatically generate one for you:
public string sessionID
{
get; set;
}
Like everyone else has already said, you are doing an infinite recursion. Unlike everyone else, I'm going to explain you why an infinite recursion causes a stack overflow:
First, you need to understand that properties are just getter and setter methods (or functions, to speak more generically), only that they have a special syntax aimed to make the code that uses them more readable.
When some code attempts to set the property, behind the scenes the setter function is called, passing the value as an argument. Internally, your s.sessionID = attributeArray[0].ToString(); is essentially s.set_sessionID(attributeArray[0].ToString());. So your setter is being called. But the setter also attempts to set the property. In fact, the sessionID = value; is just a cleaner way to say set_sessionID(value);. So your setter is invoking the setter, again. This invocation will attempt to run the sessionID = value; statement, which invokes the setter, which attempts to run the statement, which invokes the setter, which... ok, I hope you get the idea.
A function that invokes itself is said to be recursive, and the technique itself is normally refered to as recursion. There are some good uses for recursion, but normally they use some form of conditional branching (so, eventually, the condition fails and the function stops calling itself and starts yielding results). On your case, however, you are going to the infinite and beyond: there is nothing on your code to stop the recursion (mostly because it wasn't intended to be recursive after all), so it will go on indefinitely. Well, not indefinitely, just until it crashes your program :P
Now, into the juicy part of this answer: what the heck is a StackOverflow? (aside from a nice Q/A website). Why aren't you getting something like an InfiniteRecursionException? Of course, the runtime doesn't know whether you messed up or you are just doing something unusual (actually, the runtime hopes you are doing something sane), so it trusts you and keeps doing what your code is telling it to do (in this case, call the property setter).
But for a function call to work, the runtime needs to push a "pointer" to the calling statemenet and the call arguments into the stack. The pointer is needed so the runtime can figure out where to go once the called function returns. And the arguments are needed so the function will know where to look for them (after all, it doesn't know from where will it be called). On each call, these things are pushed to the top of the stack, on top of everything that was already there.
Normally, the function would pop (retrieve and remove) the arguments, do some stuff, and return. At that point (the arguments aren't there anymore), the "return pointer" is on the top of the stack, so the runtime pops it and uses it to give control back to the caller.
It is because of this stacking mechanism (everything pushed goes on top of everything else, and stuff is only popped from the top of the stack) that chained calls can work (for example: function A calls function B which calls function C: when C returns, control will go back to B, not directly to A; but once B itself returns, control does go back to A).
What happens if you keep pouring water onto a glass? Normally it will fill up (unless it has a hole or something). But what if you keep pouring water onto it when it's already full? The water flows out of the glass, because it can't fit in. We could say that the water overflows from the glass.
Now, let's look again to your infinite recursion: each time you're setting the property, you are making (implicitly) a call to the setter, so a new "return pointer" and an argument (the value) are pushed onto the stack. Since the call makes a new call before it has a chance to return, it is pushing return pointers to the stack indefinitely before they get a chance to be popped. So the stack fills up, until it has no more memory available. At that point, the stack overflows. And, because there is absolutely no way for the program to continue without pushing stuff on the stack (which the runtime can't do because there is no more room for that stuff), the only option left is to complain about the issue. This complain from the runtime is what is commonly known as a StackOverflowException.
BTW, you can see (a simplified sample) of the call stack while debugging your program. Run it through Visual Studio's debugger (by default, you can do that by pressing F5) and wait for it to crash with the SO exception. Then look for the "Call Stack" window (I can't remember where it appears by default, have moved it countless times), and you will see how deep the runtime has been able to go on the recursion before running out of stack space. Your setter should show up there line after line, countless times.
And finally, a mention on the solutions: all you need to do is to avoid recursion. This means that you can't call your setter from inside your setter (by setting the same property from the setter). This also applies to getters (which are called upon getting).
The typical way to do this is to define a "backing" field for the property (a member variable where the value will actually be stored), and then from your setter and getter you set or return that field, respectively. Since the field needs to have a different name (a typical approach is to use an underscore (_) followed by the name of the property), the compiler will know that you are setting the field and not the property, so won't try to recursively call your property's setter.
Normally, setters are useful to perform "Sanity checks" (for example, you could check that the passed value is not null), but there are many situations when there is no need for checks on neither the setter nor the getter, and having to define the backing fields and the setters/getters themselves becomes boring, bloated, redundant, and error-prone. For this reason, C# supports "auto-implemented" properties: if you replace both accessors with get; set; (and the property is not abstract), the compiler will add a "nameless" backing field and the getting/setting code for you. Note that for this to work, you have to leave both accessors: if you want to define one of them, you'll also need to define the other.
If you have already understood the concepts, loot at the other answers to see many examples on how to apply them ;)
Hope this helps.
You have to use a backing field if you implement getter and setter yourself, otherwise it will keep calling itself on the setter, i.e like this:
private string _sessionId;
public string sessionID
{
get
{
return _sessionID;
}
set
{
_sessionID = value;
}
}
Since you don't actually need the implementations as you didn't put in any custom logic, use automatic properties:
public string sessionID {get;set;}
You're assigning sessionId to itself in your set accessor. (Recursively)
You need to split the field you're assinging to it's own backing field, or use an automatic property.
Like so:
private string _sessionId;
public string sessionID
{
get
{
return _sessionId;
}
set
{
_sessionId= value;
}
}
or automatic property:
public string sessionId { get;set ;}
Also note: You're other properties are going to have the same issue when you access the set accessor.
I have a class Employee. I want to be able to Validate() it before I save it to make sure all the fields have been populated with valid values.
The user of the class may call Validate() before they call Save() or they may call Save() directly and Save() will then call Validate() and probably throw an Exception if validation fails.
Now, my (main) question is this;
If my Validate() function returns a simple bool then how do I tell the user of the class what is wrong, i.e. "Email not filled in", "ID not unique" etc. For the purposes of this I just want the error strings to pass to the human user, but the principle is the same if I wanted a list of error codes (except that makes the use of a bitmap more logical).
I could use an Out paramater in my Validate function but I understand this is frowned upon.
Rather than returning a bool, I could return a string array from my function and just test if it was empty (meaning no errors) - but that seems messy and not right.
I could create a Struct just to return from this method, including a bool and a string array with error messages, but just seems clunky.
I could return a bitmap of error codes instead of a bool and look it up, but that seems rather excessive.
I could create a public property "ValidationErrors" on the object which would hold the errors. However, that would rely on me calling Validate() before reading it or explicitly calling Validate from the Property() which is a bit wasteful.
My specific program is in C# but this looks like a fairly generic "best practice" question and one I am sure I should know the answer to. Any advice gratefully received.
I could create a Struct just to return from this method, including a bool and a string array with error messages, but just seems clunky.
Why does it seem clunky? Creating an appropriate type to encapsulate the information is perfect. I wouldn't necessarily use a string to encode such information, though. An enum may be better suited.
An alternative would be to subclass the return type and provide an extra child class for every case – if this is appropriate. If more than one failures may be signalled, an array is fine. But I would encapsulate this in an own type as well.
The general pattern could look like this:
class ValidationInfo {
public bool Valid { get; private set; }
public IEnumerable<Failure> Failures { get; private set; }
}
I would probably go for the bitmap-option. Simply
[Flags]
public enum ValidationError {
None = 0,
SomeError = 1,
OtherError = 2,
ThirdError = 4
}
...and in the calling code, simply:
ValidationError errCode = employee.Validate();
if(errCode != ValidationError.None) {
// Do something
}
Seems nice and compact to me.
I would follow the pattern of the TryParse methods and use a method with this signature:
public bool TryValidate(out IEnumerable<string> errors) { ... }
Another option is to pull the validation code out of the object into its own class, possibly building on the Specification pattern.
public class EmployeeValidator
{
public bool IsSatisfiedBy(Employee candidate)
{
//validate and populate Errors
}
public IEnumerable<string> Errors { get; private set; }
}
I have found it a good approach to simply have a method (or a property, since C# has nice support for that) which returns all validation error messages in some kind of sensible, easy to use format, such as a list of strings.
This way you can also keep your validate method returning bools.
Sounds like you need a generic class:
public sealed class ValidationResult<T>
{
private readonly bool _valid; // could do an enum {Invalid, Warning, Valid}
private readonly T _result;
private readonly List<ValidationMessage> _messages;
public ValidationResult(T result) { _valid = true; _result = result; _messages = /* empty list */; }
public static ValidationResult<T> Error(IEnumerable<ValidationMessage> messages)
{
_valid = false;
_result = default(T);
_messages = messages.ToList();
}
public bool IsValid { get { return _valid; } }
public T Result { get { if(!_valid) throw new InvalidOperationException(); return _result; } }
public IEnumerable<ValidationMessage> Messages { get { return _messages; } } // or ReadOnlyCollection<ValidationMessage> might be better return type
// desirable things: implicit conversion from T
// an overload for the Error factory method that takes params ValidationMessage[]
// whatever other goodies you want
// DataContract, Serializable attributes to make this go over the wire
}
You could take a look at Rockford Lhotka's CSLA which has extensive business rule/validation tracking forr business objects in it.
www.lhotka.net
I agree with Chris W. I asked the same questions, before reading Rocky`s Expert C# Business Objects.
He has a brilliant way of handling business validation rules. The validation is done after each property is set. Whenever a rule is broken, the object`s state become InValid.
Your business class can implement the IDataError interface. Binding your UI controls to your business object properties will then notify your ErrorProvider control of any broken rules on your object.
I would really recommend you take the time and look at the validation section.
We are using spring validation together with an Windows Forms error provider.
So our validation function returns a dictionary with a control id and an error message (for every validation error). The error provider shows the error message in a pop up field near the control which caused the error.
I used some other validation schemes in the past - but this one works really well.
Is there any way to access the backing field for a property in order to do validation, change tracking etc.?
Is something like the following possible? If not is there any plans to have it in .NET 4 / C# 4?
public string Name
{
get;
set
{
if (value != <Keyword>)
{
RaiseEvent();
}
<Keyword> = value;
}
}
The main issue I have is that using auto properties doesn't allow for the same flexibility in validation etc. that a property with a explicit backing field does. However an explicit backing field has the disadvantage in some situations of allowing the class it is contained in to access the backing field when it should be accessing and reusing the validation, change tracking etc. of the property just like any other class that may be accessing the property externally.
In the example above access to the backing field would be scoped to the property thus preventing circumvention of the property validation, change tracking etc.
Edit: I've changed < Backing Field > to < Keyword >. I would propose a new keyword similar to value. field would do nicely although I'm sure it's being used in a lot of existing code.
No there isn't. If you want to access the backing field, then don't use auto properties and roll your own.
I agree that it would be great to have a field that was only accessible by the property and not by the rest of the class. I would use that all the time.
As the MSDN states:
"In C# 3.0 and later, auto-implemented
properties make property-declaration
more concise when no additional logic
is required in the property accessors.
They also enable client code to create
objects When you declare a property as
shown in the following example, the
compiler creates a private, anonymous
backing field can only be accessed
through the property's get and set
accessors."
Since you have additional logic in you accessors, the use of auto-implemented properties is not appropriate in your scenario.
While the backing field does exist, it is given a mangled name to stop you referencing it easily - the idea is that you never reference the field directly. For interests sake, you can use Reflector to disassemble your code and discover the field name, but I would recommend you not use the field directly as this name may indeed be volatile, so your code could break at any time.
Having read your comments in Mehrdad's answer, I think I understand your problem a bit better.
It appears that you are concerned about the ability of the developer to access private state in the class they are writing, bypassing your validation logic, etc. This suggests that the state should not be contained in the class at all.
I would suggest the following strategy. Write a generic class that represents a ValidatedValue. This class holds only the backing value and only allows access/mutation via get and set methods. A delegate is passed to the ValidatedValue to represent the validation logic:
public class ValidatedValue< T >
{
private T m_val;
public ValidationFn m_validationFn;
public delegate bool ValidationFn( T fn );
public ValidatedValue( ValidationFn validationFn )
{
m_validationFn = validationFn;
}
public T get()
{
return m_val;
}
public void set(T v)
{
if (m_validationFn(v))
{
m_val = v;
}
}
}
You could, of course, add more delegates as required (eg, to support pre/post change notification).
Your class would now use the ValidatedValue in place of a backing store for your property.
The example below shows a class, MyClass, with an integer that is validated to be less than 100. Note that the logic to throw an exception is in MyClass, not the ValidatedValue. This allows you to do complex validation rules that depend on other state contained in MyClass. Lambda notation was used to construct the validation delegate - you could have bound to a member function instead.
public partial class MyClass
{
private ValidatedValue<int> m_foo;
public MyClass()
{
m_foo = new ValidatedValue<int>(
v =>
{
if (v >= 100) RaiseError();
return true;
}
);
}
private void RaiseError()
{
// Put your logic here....
throw new NotImplementedException();
}
public int Foo
{
get { return m_foo.get(); }
set { m_foo.set(value); }
}
}
Hope that helps - somewhat off the original topic, but I think it's more inline with your actual concerns. What we have done is taken the validation logic away from the property and put it on the data, which is exactly where you wanted it.
No, but you can in a subclass:
public class Base
{
public string Name
{
get;
virtual set;
}
}
public class Subclass : Base
{
// FIXME Unsure as to the exact syntax.
public string Name
{
override set
{
if (value != base.Name)
{
RaiseEvent();
}
base.Name = value;
}
}
}
If you're gonna do so, why you are using auto properties?!
A simple property has done it way back in 1.0. I don't think it makes sense to add complexity to the language for every special case. You either need the property to do plain store/retrieve model or need more than that. In the latter case, a normal property will do.
You can't do this I'm afraid. That's one of the reasons I started writing MoXAML Power Toys, to provide the ability to convert automatic properties into Notify properties.