4 ms·
The author is mistaken. You should have no getters and setters of primitive data types. There should be no private String custName; public String get custNa
by dhimes 18y ago
The author is mistaken. You should have no getters and setters of primitive data types. There should be no
private String custName;
public String get custName(){...}
public set custName(String cn){...}
The way to handle this situation is to make a custID object that contains custName, and allows you to add custAvatar, custNumber, etc., as needs change and grow. Then it's ok to have getters and setters for the custID object.
I often find that my "data" objects (custID in the above) have all public variables (that is, custName is public, custID is public, etc.). I find it preposterous to have private variables and public getters and setters that do no "processing" of the input.
The reason for encapsulating this way is that if, two years later, you find your needs change and you need other information attached to the "customer," you don't break your old contracts. It's easy to add data to the data object for the objects that now need them, and for the others to ignore it.
- Tobias42 18y agoIf you put everything important into the custID object, what is left for the customer object? Just a reference to its custID? And how does a custID object help you to avoid breaking old contracts? Adding stuff directly to the customer object wouldn't break your old contracts either. What could break your contracts however, is omitting getters and setters and just making variables public. What if you have to add some "processing" of an input later? If you have had a setter from the beginning, it can be done transparently without changing any classes that use the setter.
- dhimes 18y agoI think you are calling "customer" what I'm calling "customer ID." You then add getters and setters for the customer (custID) object. Any pre-processing is handled there. Also, some vars in the custID can certainly be handled with get/set--vars set via user input, for instance. But I also use this for building, for example, custom buttons. Things like color, stroke, etc. all set in a "buttonData" object. My custom button comes from a class that extends JButton with a constructor that accepts the buttonData object. The beauty of this is that I can add a new feature to my buttons, say transparency, but (i) modifying the new Button class to paint transparently, and (ii) adding the transparency value to the buttonData objects. Nothing else in the code has to change, and I have custom transparency. If I want a particular set of buttons to have a unique transparency, say the "help" buttons, I simply vary the value of the buttonData object before calling that constructor. This is the power of OOP: encapsulating what changes. Is it slower to build? Absolutely. But you can probably already see how simple it is to modify and maintain.