#701 – Centralize Business Rules Logic in set Accessors

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;
        }
    }
Advertisements