Tuesday, August 11, 2009

Maintenance Cost and C# Auto Properties

 

Auto properties in C# provide a simple way to implement a property on a class without explicitly creating the field that the property accessors (get and set) will work on.  There have been many discussions on whether or not auto properties are good, their advantages, and their disadvantages.  Looked at from a code-maintenance perspective, an auto property is much better.

When maintaining code, one big problem is making sure that the code you’re maintaining isn’t doing anything tricky that will make it difficult to modify or fix.  This is one of the reasons why SRP and DRY are so important.  If there’s only one place that does something and that place is only responsible for the one thing that it does, a code maintainer’s life is very joyful.  When this is not the case, a small change or fix may have detrimental repercussions.

With this in mind, there is a maintenance cost to not using auto properties.  If there’s a field hidden under your property, as a maintainer of your code, I now have to check all uses of the field as well as all uses of the property.  With an auto property, the property is the only thing that needs to be investigated.

When explicitly creating a field for a property it is important to consider the costs of doing so.  In addition, it’s important to ask if this field is really necessary.  Can all your methods access the property instead?  If so, why even have this extra level of misdirection.  Chances are YAGNI plays a big part here.

No comments:

Post a Comment