James Shore On Private Variables and Getter/Setters

It was nice to run across this post by James Shore on the silliness of default getter/setter methods. I’ve posted on this before and Alan Holub has a fairly famous/infamous rant on why Getter and Setters Are Evil.

As just one example of this, let’s look at the simple and popular “instance variables must be private” design rule.

Now for the problem with the rule. People know about the “private variables” rule but don’t think about why. So you end up with code like this. I swear to God, I see this stuff everywhere.

public class MySillyClass { 
  private string _myFakeEncapsulatedVariable; 
  public string getMyFakeEncapsulatedVariable() { 
    return _myFakeEncapsulatedVariable; 
  } 
  public void setMyFakeEncapsulatedVariable(string var) { 
    _myFakeEncapsulatedVariable = var; 
  } 
}

From a coupling standpoint, there’s very little difference between this code and a public variable. The code follows the letter of the rule, sure. But the programmer of this class clearly hasn’t thought things through. The “private variables” rule was a mere speedbump on the way to thoughtless design.

This part of the argument is down towards the bottom of a very large post. If you haven’t run across James Shore before his blog posts are often experiential and quite enlightening on Agile and XP techniques.