|
|
|
|
|
by incepted
3727 days ago
|
|
Good points except saying that getters and setters are an anti-pattern of OOP. Actually, you contradict this a few lines blow: > No, good OOP has class/object with both private state If a class has state, you have to be able to read that state or it's useless. It's a good practice overall to tell classes what to do but eventually, you need to get information from them. That's where getters come into play. |
|
No, having a bunch of getABC(), getXYZ(), getEtc() is a code smell.
If the class has many getters()+setters() or has the equivalent of many public data members, it means that related actions requiring those variables are happening outside of the class/object instead of inside the class. The more getters()/setters() made available means the more the programmer is treating the class as a "dumb struct{}" with exposed members instead of a "smart agent" with knobs & levers to direct a hidden machine. The "knobs & levers" should be higher-level public methods that are not gets()+sets().
For example, let's say we have a TextBuffer object:
With get()/set() mentality:
With a public method to make the object smarter about itself: The method CountLines() replaces gets()/sets() and makes the object more "black box". The "for(){}" loop would be inside the object.Making objects "smarter about themselves" is a hallmark of good OOP. Less exposed getters() is less coupling and less pollution of classes' internals to the outside world. Refactoring/reducing gets()/sets() means unifying those outside actions acting on object's internals into a higher-level method interface.
I'm not saying all gets() can be eliminated. But the Java practice of having 20 private member variables mirrored by 20 public gets()/sets() is not what OOP is about. It's actually about as opposite from OOP as you can get!