Java Accessors: The Good, the bad and the ugly

By Ian Darwin on 2016-01-24 19:11

Java Accessors have always been a mixed bag and a source of suspicion. Why have so much code that just sets and gets variables? Yet every "Java 101" teaches that these are the standard way of providing "encapsulation", something that 99.44% of accessors actually fail to provide!

Long ago, before the rise of the machines, I mean the IDEs, I did some tests on hand-written accessors in a large application and found about a 1/2 percent error rate. So one in every 200 accessors either set or got the wrong value! The application 'worked' at the time so these accessors were probably not used, but who knows? Nowadays most Java devs know to use their IDE to generate such things. But the question is: should they?

Here's a long list of articles that challenge the accepted wisdom:

  • http://www.javaworld.com/article/2073723/core-java/why-getter-and-setter-methods-are-evil.html (2003!)
  • http://c2.com/cgi/wiki?AccessorsAreEvil
  • http://typicalprogrammer.com/doing-it-wrong-getters-and-setters/ (2008)
  • http://www.yegor256.com/2014/09/16/getters-and-setters-are-evil.html (2014)


Twitter logo RSS/Atom Feed Icon
Categories Cloud