开发者

How do you write code that conforms to the OCP?

开发者 https://www.devze.com 2023-01-21 10:15 出处:网络
I have recently been trying to learn about basic design principles and the OCP has me a bit confused. It makes sense that when a change happens it is preferable to extend the system rather than modify

I have recently been trying to learn about basic design principles and the OCP has me a bit confused. It makes sense that when a change happens it is preferable to extend the system rather than modify existing and working parts. But isn't this more of a principle for how to implement changes in a system rather than how to design one? Isn't all code basically open for extension by using subclassing? And how can any code be closed for modification - doesn't that just depend on how the person implementing a change chooses to use it?

Pe开发者_Python百科rhaps an example of some code that doesn't follow the OCP and how exactly it has violated the principle would be the most helpful for me to understand this.

Thanks


A typical example would be any logic that branches on the type of things. Doing this means that every time you need to add a new type, you have to change this code. Using virtual functions means that you can just add new classes for new types without changing existing code.

Open Closed Principle (PDF)

There are code examples in there.

0

精彩评论

暂无评论...
验证码 换一张
取 消