Getters and Setters are bad
Briefly reading over the above article I find that getters and setters are bad OO design and should be avoided as they go against Encapsulation and Data Hiding. As this is the case how can it be avoided when creating objects and how can one model objects to take this into account.
In cases where a getter or setter is required what other alternatives can be used?
Thanks.
Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer.
Thus: you avoid getters and setters by thinking in terms of behavior, not in terms of state. Getters/setters manipulate state, from the "outside" (by doing avail = purse.
Having getters and setters does not in itself break encapsulation.
Getter and setter functions allow access to the private data in a safe mode. As the setter function C++ is used along with the data validation, and checks whether the user enters a valid value or not. In some cases, you can not use getter and setter functions.
You have missed the point. The valid, important bit of that article is:
Don't ask for the information you need to do the work; ask the object that has the information to do the work for you.
Java-style getter and setter proliferation are symptoms of ignoring this advice.
Getters or setters by themselves are not bad OO design.
What is bad is coding practice which includes a getter AND a setter for EVERY single member automatically, whether that getter/setter is needed or not (coupled with making members public which should not be public) - because this basically exposes class's implementation to outside world violating the information hiding/abstraction. Sometimes this is done automatically by IDE, which means such practice is significantly more widespread than it's hoped for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With