4 ms·
On the struct-like data objects part - this is so much nicer than the getter (and setter for mutable objects) pattern, just because readability is so much impro
by davnicwil 11y ago
On the struct-like data objects part - this is so much nicer than the getter (and setter for mutable objects) pattern, just because readability is so much improved.
Getters/setters is a pattern that it took me a while to reject, having always been told that public fields were really, really bad. But they're simply not. Having logic in getters/setters is the only justification for this added bloat. In my experience, in the overwhelming majority of cases (never say all) having logic in getters and setters is a clear indication that your design is flawed anyway, so most of the time you should never have them.
On this part:
> 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.
Well, I'd go further. Make the class final if you really want to guard against people extending it. Of course this is most applicable for writing reusable libraries where communication with consumers may be limited.
If you rely on language features to enforce development practices in a team who can freely communicate, in general you've got a much bigger problems than the few rare bugs that extending an immutable class and making it mutable will cause.
Obviously though, putting guard rails in can only ever be helpful, even when absolutely everyone understands that there's a cliff edge there, and wouldn't conciously try to walk over it anyway.
- mark_l_watson 11y agoI don't like to use getters, setters either. I like default package access so instance variables are just visible inside a package.