Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does encapsulation seem to contradict the Open-Closed principle?

In encapsulation the idea is that you hide what your class is doing with its variables by declaring them private, which achieves the OCP. But then why would you then add getters and setters, which then opens up your variables for modification?

Why go through the whole trouble of setting your variables as private, to then add a public setter on them? That doesn't seem very restrictive, which is one of the ideas of encapsulation.

like image 663
liloka Avatar asked Dec 05 '22 08:12

liloka


2 Answers

opens up your variables for modification

In Open-Closed Principle, the word "open" means something entirely different.

It means that the source code of the class is closed for modification, but the resulting class artifact is open for further modification by extension. Neither open nor closed refers to any aspect of the instances of the class.

On the other hand, I am with you on the critique of getters/setters from a slightly different angle: they add a huge amount of boilerplate just to revert your overall design to something almost identical to a class with public fields.

In some cases, which are less commonplace, it still pays to gave getters/setters. This is true for classes which belong to a public API of a library, and generally to any class which has some non-trivial behavior, configured through the setters.

For pure data classes, getters/setters are mainly forced into them by the requirements of outdated frameworks which refuse to work with public fields. Spring, Hibernate, and Jackson are examples of state-of-the-art frameworks which do not force this.

like image 194
Marko Topolnik Avatar answered May 11 '23 03:05

Marko Topolnik


Setting a variable directly gives control to outside code like

class A {
    public String a;
}
A a = new A();
a.a = "bad value which will cause code fail"

But in case of getters and setters,

class A {
    private String a;

    public void setA(String a) {
       if(! "some bad value".equals(a) ) {
           this.a = a;
       }

    }
}

So, using getters and setters will give the control with our class instance and not other possible bad class.

like image 37
Yogesh Patil Avatar answered May 11 '23 02:05

Yogesh Patil