Open/Closed Principle (OCP)

Open/Closed Principle (OCP)

S.O.L.I.D principles series

Another SOLID principles in software development is the Open/Closed Principle (OCP), which asserts that software entities should be closed to alteration but open for expansion. This means that classes have to be created such that new functionality can be added to them without requiring changes to the existing code.

In the context of musicians, we can design a basic class named Musician that includes common characteristics and methods for all musicians. Then, any particular kind of artist can add their own distinct behaviour to this basic class by extending it.

In other words, we should be able to add new functionality to a class without changing its existing code. For example, the following diagram shows a guitarist, singer and drummer classes which extends the musician class without modifying it:

In our class diagram, we have a base class Musician with a play method that all musicians can use. The Guitarist, Singer and Drummer classes extend Musician and add their own instrument-specific methods (sing, playGuitar and playDrums).

Here is the code implementation of the Open/Closed Principle diagram:

class Musician {
    public play() {
        console.log("Playing something")
    }
}

class Singer extends Musician {
    public sing() {
        console.log("Singing the lyrics");
    }
}

class Guitarist extends Musician {
    public playGuitar() {
        console.log("Playing the guitar");
    }
}

class Drummer extends Musician {
    public playDrum() {
        console.log("Playing the drums");
    }
}

// Creating instances of the musician
const singer = new Singer();
const guitarist = new Guitarist();
const drummer = new Drummer();

// Using the play method on each instance of musician and thier
singer.play();
guitarist.play();
drummer.play();

// Using the own instrument-specific method
singer.sing()
guitarist.playGuitar();
drummer.playDrum();

We can simply add new kinds of musicians in the future without having to modify the current code by adhering to the OCP principle. This encourages maintainability, scalability, and code reuse.

See you in the next article of this series.

Did you find this article valuable?

Support Max Martínez Cartagena by becoming a sponsor. Any amount is appreciated!