1

One example i can think of is Template Pattern which is a way of doing IoC is also an example of OCP. Because in template pattern we define the base algorithm which cannot be changed by child classes but can override the inherited step methods of that algorithm. So in future if we want to change the implementation of a step we can create another child class and implement those steps.

Is there any other example of this as well ?

user10916892
  • 825
  • 12
  • 33
  • I think you're on the right track. Consider additional IoC patterns and whether they might _all_ facilitate OCP for the same reasons you've described. How about Dependency Injection, for example? – jaco0646 Aug 19 '19 at 13:48
  • Some historical context is given in the tag wikis for [OCP](https://stackoverflow.com/tags/open-closed-principle/info) and [DIP](https://stackoverflow.com/tags/dependency-inversion/info). – jaco0646 Jan 03 '20 at 16:06

1 Answers1

2

The open-closed principle suggests that you should prefer things with extensible behavior so that you don't have to modify their source code when you need them to do new things.

When you do it right, inversion of control is simultaneously the simplest and most powerful way to provide this extensibility.

It's the simplest way, because when you define an injectible interface for IoC, you only capture your requirements. Other methods of configuring extensible behavior require you to think about everything consumers might want.

It's the most powerful way, because code can do anything, and providing an IoC extension point allows consumers to do all kinds of things you haven't imagined, so long as they satisfy the requirements defined by your interface. Again this is because the injected interface only captures your own needs.

So, OCP and IoC are related in a very simple way: OCP is a goal, and IoC is the means to accomplish it.

jaco0646
  • 15,303
  • 7
  • 59
  • 83
Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87