Thursday 3 March 2011

Properties versus direct access to fields

I was recently required to pick up some legacy code that included public fields along these lines:
public class SomeClass
{
    public int someInt;

    // ... snip ...
}
I have grown used to using auto-implemented properties under such circumstances:
public class SomeClass
{
    public int SomeInt { get; set; }

    // ... snip ...
}
To make matters worse different classes had different casing so sometimes public fields started with a capital and sometimes not (trivial but annoying). After my initial gasps of horror I got to thinking about the difference between exposing fields directly versus using properties. What really are the pros and cons?
MSDN describes properties in the following terms:
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.”
It turns out that Jeff Atwood is quite opinionated about the subject. Jeff acknowledges some arguments in favour of using properties over fields such as the following:
  • Reflection works differently on fields than on properties. If you rely on reflection properties are a more natural fit.
  • You can't databind against a field.
  • Changing a field to a property is a breaking change requiring client code to be recompiled.
I also think that using a property signifies intent; it identifies that you intended the encapsulated field to be exposed outside the class. In effect by using a property you are declaring part of a contract, which is probably why you can declare properties in interfaces. This opinion seems to be confirmed by Jon Skeet:
A property communicates the idea of "I will make a value available to you, or accept a value from you." It's not an implementation concept, it's an interface concept. A field, on the other hand, communicates the implementation - it says "this type represents a value in this very specific way". There's no encapsulation, it's the bare storage format. This is part of the reason fields aren't part of interfaces - they don't belong there, as they talk about how something is achieved rather than what is achieved.” - http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx
Properties also allow you to use combined access modifiers should you need to (note the private setter here):
public class SomeClass
{
    public int SomeInt { get; private set; }

    // ... snip ...
}
More verbose than simple public fields they may be, but I like properties.
Thursday 3 March 2011,