Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getters and Setters are bad OO design? [duplicate]

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.

like image 558
Julio Avatar asked Apr 30 '10 21:04

Julio


People also ask

Should you use getters and setters in C#?

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.

How do you avoid getters and setters?

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.

Do getters and setters enforce or weaken encapsulation?

Having getters and setters does not in itself break encapsulation.

Does C++ use getters and setters?

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.


2 Answers

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.

like image 108
Cory Petosky Avatar answered Sep 29 '22 20:09

Cory Petosky


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.

like image 38
DVK Avatar answered Sep 29 '22 19:09

DVK