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.
Related
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");
}
}
I have a class which implements INotifyPropertyChanged. I have a property setter which triggers notification. But the C# compiler does not know/complain anything if I just use the field, and directly assign values. But if I do that property changed notification is completely useless. I am seeing this mistake being made quite often. SO my questions are
How to verify if this mistake (setting filed value instead of using setter) is made in a large solution,
How to force some kind of warning or errors when this happens
Since no question is complete without a code sample, here is the illustration of proplem
class Person : INotifyPropertyChanged
{
private string personName;
public string PersonName
{
get { return personName; }
set { if(personName!=value)
{
personName = value;
this.OnPropertyChanged ("PersonName");
}
}
}
public bool dummy()
{
personName = "not notified"; //need to detect/avoid this
}
}
Maybe you can try an extension.
Kind Of Magic automatically adds at compile time the necessary "raisers" for you. So you can use only Auto-Implemented Properties and avoid the private field.
It works like this:
Instead of write all code:
public string Name
{
get
{
return _name;
}
set
{
if (_name != value)
{
_name = value;
RaisePropertyChanged("Name");
}
}
}
Just use an attribute to do this work:
[Magic]
public string Name { get; set; }
The extension have much more option. I think you should take a look.
Edit
If you search more you can find even more extension that try avoid type all the pattern of INotifyPropertyChanged without lose functionality.
Your code is OK. In this application properties are only WPF UI gateway. Use a following naming convention to recognize properties and fields simpler:
//Camel convention and beginning with underscore and small letter
private String _personName;
//Camel convention and capital letter beginning
public string PersonName { get; set; }
By normal, in ViewModel properties do not have to be accessed: it is commands' prerogative. All you have to do in ViewModel is to initialize private fields in constructor.
That is not kind of potential error to raise up a warning, but it may be a first step to obfuscate code a much.
Of course if you are so worried about breaking MVVM pattern principles, there is a range of frameworks which cope with MVVM routine successfully.
Also you can find it useful to refresh MVVM knowledge with some guidelines.
Which method style is better?
Is it generally bad practice to modify the variable within a method?
public class Person
{
public string Name { get; set;}
}
//Style 1
public void App()
{
Person p = new Person();
p.Name = GetName();
}
public string GetName()
{
return "daniel";
}
//Style 2
public void App()
{
Person p = new Person();
LoadName(p)
}
public void LoadName(Person p)
{
p.Name = "daniel";
}
There are times when both styles may make sense. For example, if you're simply setting the name, then perhaps you go with the first style. Don't pass an object into a method to mutate one thing, simply retrieve the one thing. This method is now more reusable as a side benefit. Think of it like the Law of Demeter or the principle of least knowledge.
In other cases, maybe you need to do a wholesale update based on user input. If you're displaying a person's attributes and allowing the user to make modifications, maybe you pass the object into a single method so that all updates can be applied in one spot.
Either approach can be warranted at different times.
I think the code is more clear and readable when methods don't change objects passed. Especially internal fields of passed object.
This might be needed sometimes. But in general I would avoid it.
Updated based on comment (good point)
I agree with Anthony's answer. There are times when both styles may make sense.
Also, for more readability you can add the LoadName function in person class.
public void App()
{
Person p = new Person();
p.LoadName(); //If you need additional data to set the Name. You can pass that as Parameter
}
You are accessing the data using properties which technically is by a methods. What you are worried is property accessing iVar or internal variable. There reason why it is generally bad to allow access of iVar is because anyone can modify the variables without your knowledge or without your permission, if its through a methods (properties), you have the ability to intercept the message when it get or set, or prevent it from getting read or write, thus it is generally said to be the best practice.
I agree with Ron. Although your particular example could be slightly contrived for posting reasons, I would have a public getter for Name, and a private setter. Pass the name to the constructor, and the Name property will get set there, but afterwards can no longer be modified.
For example:
public class Person
{
public string Name { get; private set; }
public Person( string name)
{
Name = name;
}
}
I'm taking a C# class right now and I'm trying to find out the best way of doing things. I come from a Java background and so I'm only familiar with Java best-practices; I'm a C# novice!
In Java if I have a private property, I do this;
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
In C#, I see that there are many ways of doing this.
I can do it like Java:
private string name;
public void setName(string name) {
this.name = name;
}
public string getName() {
return this.name;
}
Or I can do it this way:
private string name;
public string Name {
get { return name; }
set { name = value; }
}
Or:
public string Name { get; set; }
Which one should I use, and what are the caveats or subtleties involved with each approach? When creating classes, I am following general best-practices that I know from Java (especially reading Effective Java). So for example, I am favoring immutability (providing setters only when necessary). I'm just curious to see how these practices fit in with the various ways of providing setters and getters in C#; essentially, how would I translate best-practices from the Java world into C#?
EDIT
I was posting this as a comment to Jon Skeet's answer but then it got long:
What about a non-trivial property (i.e., with significant processing and validation perhaps)? Could I still expose it via a public property but with the logic encapsulated in get and set? Why would/should I do this over having dedicated setter and getter methods (with associated processing and validation logic).
Pre-C# 6
I'd use the last of these, for a trivial property. Note that I'd call this a public property as both the getters and setters are public.
Immutability is a bit of a pain with automatically implemented properties - you can't write an auto-property which only has a getter; the closest you can come is:
public string Foo { get; private set; }
which isn't really immutable... just immutable outside your class. So you may wish to use a real read-only property instead:
private readonly string foo;
public string Foo { get { return foo; } }
You definitely don't want to write getName() and setName(). In some cases it makes sense to write Get/Set methods rather than using properties, particularly if they could be expensive and you wish to emphasize that. However, you'd want to follow the .NET naming convention of PascalCase for methods, and you wouldn't want a trivial property like this to be implemented with normal methods anyway - a property is much more idiomatic here.
C# 6
Hooray, we finally have proper read-only automatically implemented properties:
// This can only be assigned to within the constructor
public string Foo { get; }
Likewise for read-only properties which do need to do some work, you can use member-bodied properties:
public double Area => height * width;
If all you need is a variable to store some data:
public string Name { get; set; }
Want to make it appear read-only?
public string Name { get; private set; }
Or even better...
private readonly string _name;
...
public string Name { get { return _name; } }
Want to do some value checking before assigning the property?
public string Name
{
get { return m_name; }
set
{
if (value == null)
throw new ArgumentNullException("value");
m_name = value;
}
}
In general, the GetXyz() and SetXyz() are only used in certain cases, and you just have to use your gut on when it feels right. In general, I would say that I expect most get/set properties to not contain a lot of logic and have very few, if any, unexpected side effects. If reading a property value requires invoking a service or getting input from a user in order to build the object that I'm requesting, then I would wrap it into a method, and call it something like BuildXyz(), rather than GetXyz().
Use properties in C#, not get/set methods. They are there for your convenience and it is idiomatic.
As for your two C# examples, one is simply syntactic sugar for the other. Use the auto property if all you need is a simple wrapper around an instance variable, use the full version when you need to add logic in the getter and/or setter.
In C# favor properties for exposing private fields for get and/or set. The thie form you mention is an autoproperty where the get and set automatically generate a hidden pivot backing field for you.
I favor auto properties when possible but you should never do a set/get method pair in C#.
public string Name { get; set; }
This is simply a auto-implemented property, and is technically the same as a normal property. A backing field will be created when compiling.
All properties are eventually converted to functions, so the actual compiled implementation in the end is the same as you are used to in Java.
Use auto-implemented properties when you don't have to do specific operations on the backing field. Use a ordinary property otherwise. Use get and set functions when the operation has side effects or is computationally expensive, use properties otherwise.
Regardless of which way you choose in C# the end result is the same. You will get a backinng variable with separate getter and setter methods. By using properties you are following best practices and so it's a matter of how verbose you want to get.
Personally I would choose auto-properties, the last version: public string Name { get; set; }, since they take up the least amount of space. And you can always expand these in the future if you need add something like validation.
Whenever possible I prefer public string Name { get; set; } as it's terse and easily readable. However, there may be times when this one is necessary
private string name;
public string Name {
get { return name; }
set { name = value; }
}
In C# the preferred way is through properties rather than getX() and setX() methods. Also, note that C# does not require that properties have both a get and a set - you can have get-only properties and set-only properties.
public boolean MyProperty
{
get { return something; }
}
public boolean MyProperty
{
set { this.something = value; }
}
First let me try to explain what you wrote:
// private member -- not a property
private string name;
/// public method -- not a property
public void setName(string name) {
this.name = name;
}
/// public method -- not a property
public string getName() {
return this.name;
}
// yes it is property structure before .Net 3.0
private string name;
public string Name {
get { return name; }
set { name = value; }
}
This structure is also used nowadays but it is most suitable if you want to do some extra functionality, for instance when a value is set you can it to parse to capitalize it and save it in private member for alter internal use.
With .net framework 3.0
// this style is introduced, which is more common, and suppose to be best
public string Name { get; set; }
//You can more customize it
public string Name
{
get;
private set; // means value could be set internally, and accessed through out
}
Wish you better luck in C#
As mentioned, all of these approaches result in the same outcome. The most important thing is that you pick a convention and stick with it. I prefer using the last two property examples.
like most of the answers here, use Automatic properties. Intuitive, less lines of code and it is more clean. If you should serialize your class, mark the class [Serializable]/ with [DataConract] attribute. And if you are using [DataContract] mark the member with
[DataMember(Name="aMoreFriendlyName")]
public string Name { get; set; }
Private or public setter depends on your preference.
Also note that automatic properties require both getters and setters(public or private).
/*this is invalid*/
public string Name
{
get;
/* setter omitted to prove the point*/
}
Alternatively, if you only want get/set, create a backing field yourself
Which one should I use, and what are the caveats or subtleties involved with each approach?
When going with properties there is one caveat that has not been mentioned yet: With properties you cannot have any parametrization of your getters or setters.
For example imagine you want to retrieve a list items and want to also apply a filter at the same time. With a get-method you could write something like:
obj.getItems(filter);
In contrast, with a property you are forced to first return all items
obj.items
and then apply the filter in the next step or you have to add dedicated properties that expose items filtered by different criteria, which soon bloats your API:
obj.itemsFilteredByX
obj.itemsFilteredByY
What sometimes can be a nuisance is when you started with a property, e.g. obj.items and then later discovered that getter- or setter-parametrization is needed or would make things easier for the class-API user. You would now need to either rewrite your API and modify all those places in your code that access this property or find an alternative solution. In contrast, with a get-method, e.g. obj.getItems(), you can simply extend your method's signature to accept an optional "configuration" object e.g. obj.getItems(options) without having to rewrite all those places that call your method.
That being said, (auto-implemented) properties in C# are still very useful shortcuts (for the various reasons mentioned here) since most of the time parametrization may not be needed – but this caveat stands.
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.