3 ms·
I think it's strange that people complain about the verbosity and boilerplate getters and setters in Java when this is entirely a non problem, provided your cod
by cultureswitch 3y ago
I think it's strange that people complain about the verbosity and boilerplate getters and setters in Java when this is entirely a non problem, provided your code is well designed.
If your class has any setter function, you're doing OO wrong. Mutating an object should 1) only happen if you have a very good, inescapable reason; 2) never be exposed directly to code outside the class, including children. If your class must have a mutating function, it should be a high level operation, not "set". If it really is "set" then that implies the field being set isn't a part of that object in any real sense.
A well designed class might have a couple of getters, but the inclusion of getters is a deliberate decision to allow client code to see the internal state.
In other words, blame the IDEs for the idea of auto-generating getters and setters. The language itself did a decent job of protecting class state.
- kazinator 3y agoOOP is routinely used with stateful, mutating objects; it has been hailed as a good way to manage that paradigm. If mutation is bad, so most objects don't mutate, you're talking about a functional niche in OOP, not mainstream OOP. A class may need a setter function for some boring, pragmatic reason like, say: - the language doesn't have keyword parmeters: constructors have only positional parameters - the class has a large number of properties. - most users set only a small subset of the properties, defaulting the rest. (And you can't easily predict which subsets are popular enough to get their own constructor variants.) In that situation you might want to just construct the object in two steps: default everything and set a few selected properties (and then don't touch them). It's de facto immutable, just not around construction time.
- raverbashing 3y agoI almost agree with you, I don't agree with the gatekeeping/nitpicking of saying "you're doing it wrong" But I do agree that in most cases you don't need to call individual setters. And especially not automatically create one for every variable in your class