Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning and reasoning behind the Open/Closed Principle?

The Open/Closed Principle states that software entities (classes, modules, etc.) should be open for extension, but closed for modification. What does this mean, and why is it an important principle of good object-oriented design?

like image 200
Phillip Wells Avatar asked Sep 12 '08 13:09

Phillip Wells


People also ask

What is meant by the open-closed principle?

In object-oriented programming, the open–closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"; that is, such an entity can allow its behaviour to be extended without modifying its source code.

What is open close principle with example?

The Open-Close principle (OCP) is the O in the well known SOLID acronym. A module will be said to be open if it is still available for extension. For example, it should be possible to add fields to the data structures it contains, or new elements to the set of functions it performs.

What fact does the open closed SOLID design principle represent?

The idea of open-closed principle is that existing, well-tested classes will need to be modified when something needs to be added. Yet, changing classes can lead to problems or bugs. Instead of changing the class, you simply want to extend it.

How is open-closed principle achieved?

the open/closed principle is generally achieved by using inheritance and polymorphism.


1 Answers

It means that you should put new code in new classes/modules. Existing code should be modified only for bug fixing. New classes can reuse existing code via inheritance.

Open/closed principle is intended to mitigate risk when introducing new functionality. Since you don't modify existing code you can be assured that it wouldn't be broken. It reduces maintenance cost and increases product stability.

like image 96
aku Avatar answered Oct 10 '22 18:10

aku