Open-closed principle

adel kamel
2 min readNov 29, 2023

--

open-closed principle is the second principle in SOLID

The Open-Closed Principle means that classes should be open for extension and closed to modification.

What does that mean ?

Modification means changing the code of an existing class, and extension means adding new functionality.

so why this principle is important ??

let’s say that We need to add new functionality without touching the existing code for the class. This is because whenever we modify the existing code, we are taking the risk of creating potential bugs. So we should avoid touching the tested and reliable (mostly) production code if possible.

example code that violets open-closed principle :

we have printQuiz function that loop over questions and prints them based on the question type ,

let’s say that , if we need to add another question with different type like ( range question ) what we will do ,

we will add this question to questions array and modify the switch statement to be able to print the the new question type , but that violets open-closed principle because we modified the actual code in printQuiz function.

actually if you see an switch or if statement inside function , this function violets the principle

so , what we will do ???

we will define class for each question type inside that class function to print the question choices

and we remove the switch statement from print quiz function

this is the final code

now if we need to add another question with different type , we create a class for it and add an instance of that class in the questions array without modifing the printQuiz function

finally our code is closed for modification and open for extension and implemented the open-closed principle

--

--

adel kamel
adel kamel

Written by adel kamel

0 Followers

web developer | MERN Stack

No responses yet