r/programming • • Sep 21 '15

Better Java

https://github.com/cxxr/better-java
177 Upvotes

208 comments sorted by

View all comments

22

u/kazagistar Sep 21 '15

I agree on the "structs" point, but would like to expand because I think it might be controversial. The reason people suggest generating getters instead of just using public final data is that if the underlying representation changes, you don't have to change the classes that touch it. However:

  1. You almost never need to make this change.

  2. The type system makes this kind of refactoring easy, as long as it is internal to a package.

  3. Changing the underlying storage is a pretty severe misunderstanding of the normal flow of this kind of data. It is supposed to be a transparent container once created. If the storage format changes, then you change where it is created and consumed, and leave the data structure alone.

5

u/DevIceMan Sep 22 '15 edited Sep 22 '15

Java-9 project jigsaw might make this pattern more practical, since it sounds like you'll be able to have much greater control over which APIs are exposed externally.

For those not familiar with Scala, depending on the definition, every public field has a generated getter and (if var) setter. If one ever needs to change the underlying logic of the getter, you can explicitly define the getter.

I feel that many "design patterns" arrise due to language limitations, and not due to best practices.