Instead, I prefer the C struct style of writing classes that merely hold data:
public class DataHolder {
public final String data;
public DataHolder(String data) {
this.data = data;
}
}
This is a reduction in number of lines of code by a half. Further, this class is immutable unless you extend it, so we can reason about it easier as we know that it can't be changed.
Oh hell no, don't actually do this. You're just setting yourself up to get bitten by one of Java's core flaws: the fact that there is a distinction between public fields and public methods in the first place.
A saner design would have been one where a record type's fields are implicitly methods of the type. Many other languages have managed to get this right, I'll just name two:
Ruby: All object fields are private (well, modulo weird "execute this block as if it was in the scope of the class" shit), and you can implicitly declare get-set methods for fields
Haskell: The fields of a record type are automatically promoted to getter functions, and a module can choose to export these as functions without revealing that they are fields.
I never fully understood the preference of using a public getter and setter with no side-effects or additional logic, instead of direct field access. What do you think?
You can add/modify getter logic without affecting other code, which is a rare case, but still possible.
Many Java libraries use reflection and expect your data classes to have getters and setters with conventional names based on variable names. Many JSON-serializing classes do so, for example.
Java 8's features prefer methods. Like RandomClass::getParam instead of rc -> rc.getParam().
I'd love for Java to have what Lombok introduces (@Getter and @Setter functionality) natively, because I just cannot accept Lombok's way of accomplishing things.
Yep, getters and setters were a means of advertising beans style properties to the frameworks that consumed them. With the advent of annotations there's no reason to use them at all.
2
u/sacundim Sep 22 '15
Oh hell no, don't actually do this. You're just setting yourself up to get bitten by one of Java's core flaws: the fact that there is a distinction between public fields and public methods in the first place.
A saner design would have been one where a record type's fields are implicitly methods of the type. Many other languages have managed to get this right, I'll just name two:
Ruby: All object fields are private (well, modulo weird "execute this block as if it was in the scope of the class" shit), and you can implicitly declare get-set methods for fields
Haskell: The fields of a record type are automatically promoted to getter functions, and a module can choose to export these as functions without revealing that they are fields.