| >If a class has state, you have to be able to read that state or it's useless. ... 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: TextBuffer.setLinecount(0); // reset counter to 0
for() {
TextBuffer.getNextLine();
n=n+1;
}
TextBuffer.setLinecount(n);
With a public method to make the object smarter about itself: TextBuffer.CountLines();
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! |
Maybe people are just confusing different sides of the same concept. There are smart objects as you mention and dumb data holders that are used to pass 'messages' around. The classic anemic data model, with objects that operate on said data.