#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
                if (value != age)
                    if ((value > 0) && (value < 30))
                        age = value;
                        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;

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #701 – Centralize Business Rules Logic in set Accessors

  1. 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!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: