Search code examples
oopdesign-patternssolid-principlesopen-closed-principle

Does the "Open for extension, closed for modification" principle make any sense?


It looks to me like Bob Martin needed something starting with O to make SOLID and found in some old book this (possibly useless) Open/Closed principle.

How can Open/Closed co-exists with the Single Responsibility, that states a class should have a single reason for change?

If I want to follow Open/Closed in a long living system, am I supposed to have a chain of dozens/hundreds classes, each extending the previous?


Solution

  • The Open/closed principle implies that you can create systems in which new features are added by adding new code as opposed to changing old code. In order to be perfectly conform to the open/closed principle one must have perfect foresight. For in order to create a system that is fully open to extension and closed to all modification one must be able to perfectly predict the future. One must know in advance what new features the customer will request in order to put extension points to the code.

    Having said that we could develop systems that conform well enough to the open/closed principle. By using an iterative process with lots of feedback and refactoring we can improve the parts of the system that change most often by making them open to extension and closed to modification.

    As Bob Martin says in one of his lectures: "We cannot completely conform to the open/closed principle. It doesn't mean we should simply give up on the open/closed principle entirely. It may be difficult to make the entire systems to conform to the open/closed principle but it's not difficult to make functions or classes or smaller components to conform to the open/closed principle"