by BehindJava

What is Open-Closed Principle in SOLID Design Principles of Object Oriented Programming

Home » java » What is Open-Closed Principle in SOLID Design Principles of Object Oriented Programming

Open-Closed Principle

  • A class should be open for extension but closed for modification.
  • When we have to add a new feature, existing code shouldn’t be modified.
  • This principle makes you avoid two things.

    1. Harding coding values
    2. Make code modular

Example:Suppose you want to use ingestion framework in the application which means getting the data from outside and ingesting it into the database.

class Ingest{
    public void saveData()
    {
        //Code to save data
    }
}

Lets say we are saving the credit card information of the client into the database and tomorrow we have a requirement to perform analytics on this particular data to provide better offers to the clients using credit cards.

To do so we need to ingest this data into Hadoop Distributed File System and run few jobs or Machine learning jobs or spark queries on the existing credit card data.

To achieve this for saving the data into the HDFS(Hadoop Distributed File System). We need to re-write the existing code which breaks the Open-closed principle. Instead, we can create an interface called ingest with one method called save data and every time when we want to ingest the data into a new sync or new database we can write the concrete implementation for respective database.

Interface Ingest{
    public void saveData();
}
class IngestintoHDFS implements Ingest{
    @Override
    public void saveData(){
        //save to HDFS
    }
}

Open-Closed principle saves the effort of re-testing the existing code and safeguards the code form new bugs.