Wednesday, May 18, 2011

Properties vs. Public Variables

I occasionally see code with properties like this:
private int name;
public int Name{
    
get { return name; }
    
set { name = value; }
}


Why waste everyone's time with a bunch of meaningless just-in-case wrapper code? Start with the simplest thing that works-- a public variable. You can always refactor this later into a property if it turns out additional work needs to be done when the name value is set. If you truly need a property, then use a property. Otherwise, KISS!
Update: As many commenters have pointed out, there are valid reasons to make a trivial property, exactly as depicted above:
  • Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
  • You can't databind against a variable.
  • Changing a variable to a property is a breaking change.
It's a shame there's so much meaningless friction between variables and properties; most of the time they do the exact same thing. Kevin Dente proposed a bit of new syntax that would give us the best of both worlds:
public property int Name;
The really important thing to take away here is to avoid writing code that doesn't matter. And property wrappers around public variables are the very essence of meaningless code.

No comments:

Post a Comment