SOLID - Open/Closed principle in Javascript




In this article, we shall focus on the Open/Closed principle of SOLID principles.

Open/Closed Principle

Bertrand Meyer, who gave an explanation to Open/Closed Principle as

"Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification."

This means, that our coding should be written in such a way that a class or a module or a function can allow us to add new functionality but it should not allow change to the existing code.

Below is the code which satisfies the Single-Responsibility Principle, but it violates the Open/Closed Principle.

In the above coding, the function formatMessage() gets the content and type as its parameter. Based on the type parameter the resultMessage will be formed.

Suppose, if we want to add a new type, say 'warning' then we are supposed to add a new else-if condition to check the type to be 'warning' and change the resultMessage string.

So this type of modification violates the Open/Closed Principle. The function formatMessage() should be closed for modification. To rectify this code we have to make changes to the code as below

Here, we have created a class named Logger, which takes an object as a parameter in its constructor. The parameter object can be the instances of a class. The Logger class will have a function named log() which uses the parameter object which is logObject to call a function getMessage() to form and return the result message. Then the returned result message will be printed to the console.

If we need to print the error message then we create the instance of ErrorLog class and return it as the parameter during the instantiation of the Logger class.

const successLogger = new Logger(new SuccessLog());

Now if we need to print any warning message, then we need to create a new class like SuccessLog and ErrorLog with getMessage() function.

Now to print a warning message, we will simply pass the instance of the Warning class to the Logger class instantiation. When rewriting the code, it looks something like the below code.

Running the above code will produce the following output:

Success: Employee information saved successfully - Fri Jan 03 2020 23:12:55 GMT+0530 (India Standard Time)
Error: Error has occurred. - Fri Jan 03 2020 23:12:55 GMT+0530 (India Standard Time)
Warning: This method is depricated. - Fri Jan 03 2020 23:12:55 GMT+0530 (India Standard Time)

Most Read