#701 – Centralize Business Rules Logic in set Accessors
October 26, 2012 1 Comment
You can use a property’s set accessor to enforce business rules for that property, e.g. min/max values for the property.
If you have a constructor that accepts initial values for some properties of a class, or methods that accept values, you can avoid checking constraints on these parameters by delegating the enforcement of the rules to the set accessor.
For example:
public class Dog { // Public properties public string Name { get; set; } private int age; public int Age { get { return age; } // Set accessor checks for valid Age values set { if (value != age) { if ((value > 0) && (value < 30)) age = value; else throw new Exception("Age is out of range"); } } } // Constructor public Dog(string name, int age) { Name = name; // Don't validate age value here, but let set accessor do it Age = age; } }
that’s one of the worst practices ever. they are called accessors for a reason. I expect nothing more than accessing fields. code like that makes me cry. when the style cope even recommends such a style, create a setter instead of method with void arg, then it really makes me wish to drop from the C# bang wagon!