Search code examples
software-designsolid-principles

How to achieve open-closed principle?


I have 2 classes:

public class Dog{

    public void talk(){
        
         System.out.println("dog is talking");
    }

    public void eat(){
         
          System.out.println("dog is eating");
    }
}
public class Cat{

    public void talk(){
        
         System.out.println("cat is talking");
    }

    public void eat(){
         
          System.out.println("cat is eating");
    }
}

The book says this code violates the "open-closed" principle but it doesn't give me the reason, and the answer given is that I need to create an interface to achieve that principle (also there is no explanation for that answer).

I found this article:http://joelabrahamsson.com/a-simple-example-of-the-openclosed-principle/, but in this code, if I want to add another class "bird", it won't affect the original code. So I think this code doesn't violate the "open-closed" principle.


Solution

  • Open-Closed Principle suggest us not to make changes in our existing class, otherwise please make that class extendable.

    Please note that we can still make changes but that changes should be as minimum as possible.

    In your provided code above, I don't see any violation of Open-Closed Principle because each class has their own function like talk() and eat().

    But, if you continue using that code without any abstraction (like Interface or Abstract Class), you will have great chances of violating Liskov Substitution Principle and Dependency Inversion Principle.

    You can read my article about S.O.L.I.D. Principle here. It contains simplified explanation and both Violation & Correct Example.