Reputation: 2678
I am really confused about two topics:
1)- Code duplication (I understand very well)
2)- Open-Close Principle (Need explanation when to use it? Which scenarios)
What happened is during an implementation of a new feature, my colleague told me to add a new function (method) in an existing class which was doing a specific job. The problem is that this new function had to do something that was not fine to be in that class. I told him to extends that class and add the function into this new class. He told me if we do that we are going to fall into code duplication but for me, as Junior Developer I was thinking about Open-Close Principle.
So when we should use Open-Close Principle?
Upvotes: 0
Views: 189
Reputation: 277
Open-Close Principle is about Open for Extensions and closed for Modifications. This should not be mistaken as you can never modify a code once implemented. Principle is only applicable until the next requirement change where code modification is inevitable.
However, if u understand the fine point addressed in this principle, you can get a massive benefits the principle grantees to offer you. That is having extended functionality to your deployed application just by replacing say a dll module in application deployment folder. The extended behavior is gained simply by replacement of binary file (which you can keep handy), not by code modification to application or its related module. Hence the name Open for Extensions and closed for Modifications
To gain this, you have to implement Open close principle in your development. Rule to follow is not as complex as you think. I have demonstrated the whole thing in detail with working, downloadable code sample in my tech blog. Please visit and get an idea. You will get good idea on how simple it is to apply at least 3 SOLID principles by reading this article here
Happy applying of SOLID principles!
Upvotes: 1