Re:Better Java – Resources for Writing Modern Java
by PascalW on Sunday September 20, 2015 @03:40AM
(#10246854)
I'm surprised I haven't seen anybody mention the "public final fields" approach yet. I use this myself for immutable objects and I quite like it. Granted, you still need to implement equals and hashcode, but these can be generated easily and verified with tools like EqualsVerifier [2].
[1]
public class MyImmutable {
public final String field1;
public final int field2;
public MyImmutable(String field1, int field2) {
// assign
}
// equals, hashcode, toString
}
[1]
[2] https://github.com/jqno/equalsverifier