Open/Closed Principle

Taylan Can Hardal
2 min readFeb 21, 2022

--

Hey everybody it is second principle of SOLID Principles. This principle means that a class or method should be open for extension but closed for modification. So improve your code without changing.

Let’s look at the cars. A car has thousand of items; Mirrors, fenders, wheels, doors , hoods , suspension and for example you want to improve your car. You bought new enginee and went to car mechanic. The car mechanic said to you “ I can’t do. You should buy a new car”. Isn’t that illogical? Our software entites should not be like that. We don’t want to change everythink.

Why are these principles important?

This principles are not rule. The developers use for clean code. Coding can be done without this principles but diffucult to read and debug. On the other hand, developers who have just joined the team can adapt to the project more easily.

Meanwhile, Robert C. Martin accepts this principle as the most important principle.

Example Project

In order to learn in detail, the correct usage and the wrong usage should be examined together.

Wrong Usage :

We have 2 classes. AreaCalculator class is doing calculate area but just for Rectangle. If we need to calculate Circle area this class can’t do that. So we can’t change source code because of principle but we can improve. Therefore we write a new class structure.

Correct Usage :

We created an abstract class called shape. We derived our shapes by inherited from this class. Finally Area func is calculate all of areas.

You can continue reading here :

References:

https://medium.com/swift-india/solid-principles-part-2-open-closed-principle-bf0514b824ca#:~:text=Earlier%20Open%2Fclosed%20principle%20was,without%20altering%20it's%20source%20code.

bolŞans…

--

--

Taylan Can Hardal
Taylan Can Hardal

Written by Taylan Can Hardal

Software Engineer @Turkcell. Savin’ the Earth. Somewhere

No responses yet