Tuesday, 16 October 2012

Superfluous accessors


I've been complaining about this boilerplate pattern for a while now, but what I saw today made me a bit concerned.

It is finally becoming more and more common to correctly encapsulate fields, thus getting rid of uncontrolled modifications. But the more I think about it, the more useless in certain situations. When you only have a POJO without an interface, and you have absolutely no logic around setting or retrieving a value, there is absolutely no reason to add the boilerplate accessors.
There are a finite number of keystrokes left in your hands before you die. - Scott Hanselman
It is just a perfect waste of keystrokes. I would challenge such case though, and advise you to code towards interfaces, and not implementation. There are indeed some valid cases where you'll choose to upset the gods of clean code and sacrifice a tamagotchi later on instead.

With the great power of modern IDEs, when the time should come when you'll need an interface or some logic in the getter or setter, you can use the dark powers of the "encapsulate fields" refactoring. This will hide your field from the outside world, create the accessors, and replace all read and write operations with the appropriate method call.

1 comment :

  1. I don't think so. If you use it like a data structure, then you are right. But if you manage it like an object, you must hide the representation of your object. If you put your instance variable in the public space, people start to use it and later will be harder to debug and make changes on your app. You are right in open a new interface when it is necessary, but use methods to change the object's state anytime if you use it as an object! (Sorry, I come from the Ruby world, where every instance variable is private.)


Note: only a member of this blog may post a comment.