Objects or Entities (classes, modules, methods/functions, etc.) should be Open for Extension, but Closed for Modification.

  • Entities behavior can be changed without the need to edit and recompile the code itself.
  • The Open-Closed Principle can also be achieved in many other ways, including through the use of inheritance or through compositional design patterns (e.g. Strategy pattern).

Example 1:

  • Create a Base class with Required functionality, and ensure we will not modify that class. (Closed for modification)
  • Create a Derived class by inheriting the Base class for extension (Open for modification)

 

  • public class BasicFileLogger : Logger
    Here we are extending/changing logger functionality using inheritance so that logger will have functionality related to file logging. Code Sample