Darwin's Theories Blog

New Theories for a New Time

Java Accessors; The Good, the bad and the ugly

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:

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