Saturday, April 21, 2018

On preferring the use of getters over direct field access

You often find advice that says you should prefer getters over directly using a field. Fowler terms this SelfEncapsulation. I've sometimes thought this is a bit abstract and a case of over-engineering...but today I found a good reason why it's necessary. Consider the following code: It turns out this NPE happens because of the implementation of java.io.File#isInvalid. Because this uses this.path instead of getPath(), even providing a canned answer for an external mock doesn't work well. Since #isInvalid is final (but according to the JavaDoc has rudimentary logic that they probably intend to evolve). Encapsulating even your use of private fields behind getters provides unexpected hooks for testability and maintainability.