javasolid-principlesopen-closed-principle

Open/Closed principle query


Just a quick one, so following the open closed principle, if you had a class like so:

public class Employee extends Person {
    int age;
    String name;

    Employee(int age, String name) {
        super(age, name)
    }
    
    // Getters and setters follow
}

If you wanted to add an additional field, let's say an address, wouldn't this be breaking the Open/Closed principle?

Just curious if you are breaking that principle doing that, how would you create the class to work around this issue?

Thanks


Solution

  • The short answer is "yes". It would be a violation of OCP. So, to answer your question (how would you create the class to work around this issue), Let's see what OCP is first:

    Open/Closed Principle

    OCP states that software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

    You clearly understand the last part, but you appear to miss on the first part. Again, the short answer to your question is to simply extend your original class.

    public class Person {
       int age;
       String name;
       // rest of class omitted
    }
    

    // This class already obeyed OCP by extending Person and adding new attributes and behaviors (took the liberty to change your original class for a good reason - See Person class)
    public class Employee extends Person {
       String empID;
       // Rest of the class omitted
    }
    

    // Simply add one more (corny class name, sorry)
    public class AddressableEmployee extends Employee {
       private String address;
       // Rest of the class omitted
    }
    

    This is how to obey OCP when adding new functionality. Obviously, if this is abused, it leads to class explosion which is also bad. As a developer (and designer) you must weight blindly respecting this principle against creating deep hierarchical chains.

    The thing to remember is that OCP (as the rest of SOLID) are simply recommendations. Lastly, if you find yourself in this situation, it might be an indicator of hasty design decisions (went straight to implementation without taking adequate time to solidify your design). So, instead of taking another hasty implementation decision, stop and consider redesigning what you created originally (i.e. consider composition over inheritance).