Getters and Setters are bad OO design?

15,527

Solution 1

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.

Solution 2

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.

Solution 3

Yes, getters and setters is an anti-pattern in OOP: http://www.yegor256.com/2014/09/16/getters-and-setters-are-evil.html. In a nutshell, they don't fit into object-oriented paradigm because they encourage you to treat an object like a data structure. Which is a major misconception.

Solution 4

I believe in including setters in the API only if they are really part of the class specification (i.e. its contract with the caller).

Any other data member related to inner representation should be hidden, and I see at least 2 major reasons for that:

1) If inner representation is exposed, design changes are more problematic in the future, and require API changes as well.

2) Exposing data members with setters/getters with no caution allows callers to ruin the class invariant very easily. Objects with inconsistent state can cause bugs which are very difficult to analyze.

Unfortunately there are some frameworks which encourage (sometimes require) adding setters/getters for everything.

Solution 5

Getters and setters are not bad by themselves. What is bad is the practice of making any field to be private and provide getters/setters for all of them no matter what.

Share:
15,527
Julio
Author by

Julio

Updated on June 03, 2022

Comments

  • Julio
    Julio about 2 years

    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.