Open Closed principle

Open Closed Principle – SOLID Principles

Design Principles, Featured, Javascript, OOPS

So in the previous post we have discussed the first principle of SOLID principles Single Responsibility Principle provided by Uncle Bob (Robert C. Martin) by the year 2000. In this post we are going to discuss the second principle Open Closed Principle – SOLID Principles

A Class should be open for extension but closed for modification.

This means that we should design a class in such a way that in future we can extend the class easily and do not modify it. So the new functionalities should be added in extended classes.

Lets see a simple example :

class DecimalToBinary {
  dec2bin(number) {
    return parseInt(number, 10).toString(2);
  }
}

In the above function we are converting decimal number into binary number. But what if we want to convert decimal number to hexadecimal and so on ?

If we change the DecimalToBinary Class it is a violation on Open Closed Principle. Lets check the better approach.

The Better Approach – Open Closed Principle

class NumberConverter {
  isNumber(number) {
    // Just an example of a helper function
    return true;
  }

  convertBase(number, fromBase, toBase) {
    // A naive implementation without error checking etc.
    return parseInt(number, fromBase).toString(toBase);
  }
}

class DecimalToBinary extends NumberConverter {
  isDecimalNumber(number) {
    // Just an example of a helper function, not actual implementation
    return true;
  }

  dec2bin(number) {
    return this.convertBase(number, 10, 2);
  }
}

class BinaryToDecimal extends NumberConverter {
  isBinaryNumber(number) {
    // Just an example of a helper function, not actual implementation
    return true;
  }

  bin2dec(number) {
    return this.convertBase(number, 2, 10);
  }
}

Now in the above function we have created a new class NumberConverter which is responsible to check the type of number and has an method convertBase. convertBase takes parameters such as from base (decimal) , to base (Hex), it has only one responsibility to convert the number from one base to other base.

Now the other classes can extend NumberConverter class and write its own method dec2bin or bin2dec. This is how we have achieved Open Close principle by making NumberConverter class which is open for extension but we don’t have to make any modification in it.

By using OCP with single responsibility principle we can achieve a hierarchy of classes with a good project structure.

References :

https://dev.to/carstenbehrens/solid-open-closed-principle-in-javascript-2a1g

Leave a Reply