Open/Closed Principle: Extend Your Code Without Breaking It! The Open/Closed Principle (OCP) is one of the most powerful yet underrated principles in the SOLID design principles. It states: "Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification." But what does that mean? 🤔 Let's simplify. Breaking It Down: 1. Open for Extension 🚀 Your code should allow new functionality to be added without needing to change the existing code. 2. Closed for Modification 🔒 Once your code is written, it shouldn't need to be altered to accommodate new requirements. Essentially, OCP ensures stability in your existing code while allowing for growth and new features. Benefits of OCP 🌟 1. Reduces Risk: Minimizes the chance of breaking existing functionality. 2. Eases Maintenance: Clean, modular, and easy-to-extend code. 3. Encourages Reusability: Extensible systems are inherently more reusable. Tip: Embrace polymorphism, interfaces, and abstraction to achieve OCP in your designs. How have you implemented OCP in your projects? Share your thoughts below! 👇 Let's make our systems scalable and bulletproof!
A method is not completely good or completely bad, example above with OCP consumes more source at first glimpse because repeats same code with small modification.
nice example , Thank you Ayman for sharing 👍
How can I set discount.ApplyDiscount(amount) to determine which class to use: PremiumDiscount or RegularDiscount? I think registering dependencies in the startup will cause ambiguity because register one interface in many class implement.
Looks great But it does feel like something that's reserved for complicated or for easier video game mod integration
The Open/Closed Principle is a game-changer for maintainable code, thank for sharing!
Nice share Ayman. How to implement with Aso.Net core?
Thanks for sharing Ayman Anaam OCP is such a foundational principle for scalable and maintainable code. Using interfaces and polymorphism, I was always balance to keep the code simple.
In your example it is excessive to apply the OCP. As your example is written in C#, it was more than enough to use switch expression and that's all: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression
Freelance Software Developer
5moSurely it would be the consumer of the classes in your second example that would violate OCP. You would need a strategy, factory, dependency injection or some other mechanism to choose the correct concrete class. Iit’s there your OCP implementation problems would lie.