O as Open-closed principle

By | February 19, 2020

Open/closed principle

All classes should be open for enlargement and closed for modifications.

This principle is about two things:

  1. Open — Elements should be created in a way to be easily expanded. Changes in their behavior should not require modification of the current code but added a new one.
  2. Closed — Behavior modification should not be connected with changes in existing code.

This rule we can use in methods, functions, classes, modules and packages. To apply this principle, we can use Single responsibility Principle and Dependency inversion principle.

Advantages

  • Greater flexibility.
  • Greater code reuse.
  • Easier maintenance.
  • Easier application improvement.
  • Backward compatibility.

Disadvantages

  • Greater difficulty and labor consumption during software development.

Example

  • Calculator, which counts figures area. It iterates figures. Every figure implements IFigure interface. This calculator call on every figure the method GetArea(), instead of has a switch and calculate in Calculator every area.
  • Report generators create different reports. Report generators implement IReportGenerates. We can put this report generators in clients depend on client specifications (for instance they want Pdf, Html).

All posts from mini project: Learn SOLID and OOP principles:

Sources

Main image

Materials

Leave a Reply

Your email address will not be published. Required fields are marked *