javaencapsulationopen-closed-principle

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.


Solution

  • 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.