Saturday, 1 September 2007

Getters and setters: a rant of anti-patterns

It's been at least a couple of days since my last rant, so I figure that it's time again to show a couple of things that I consider to be anti-patterns. First off, let me tell you that I get annoyed by getter and setter methods that are not just an mutator for the class. I understand that rules are made to be broken, but they should only be broken in special cases: not as the "default".

"Helpful" getter methods:
public List getFoo() {
if (this.foo == null) {
foo = new ArrayList();
}
return foo;
}

I do not think that a "getter" should change the internal state of an object. A null list isn't the same thing as an empty list. If you want to initialize it, do that in the declaration or in the constructor, not in the getter method. If for whatever reason it's not valid to have the member be null, init it and then guard against it being set to null in the setter. If you're lazy like me and you use something like Commons Lang for your equals and hashcode impl, then if you call the getter on an object, it will no longer be equal.


I had it all planned to write at least one more "issue", but I can't think of it right now. One thing at a time. ;-)

No comments:

Post a Comment