Balancing OCP with Simplicity
What you'll learn: How to apply the Open/Closed Principle without creating unnecessary complexity or over-engineering your code.
The Tension Between Extension and Over-Engineering
The Open/Closed Principle (OCP) encourages building software that's open for extension but closed for modification. However, this can tempt you to create elaborate abstraction layers for every possible future change—even ones that may never happen. This directly conflicts with YAGNI (You Aren't Gonna Need It), which warns against building features or flexibility you don't currently need.
When Abstraction Becomes Premature
Imagine designing a simple calculator app. You could create an abstract Operation interface with implementations for Addition, Subtraction, etc., anticipating you might add dozens of operations later. But if your requirements only call for basic math and no extension is planned, you've just added complexity for a hypothetical future.
Premature abstraction means introducing interfaces, inheritance hierarchies, or plugin systems before you have concrete evidence they're needed. This violates both YAGNI and KISS (Keep It Simple, Stupid).
Finding the Right Balance
Apply OCP when:
- You have actual evidence that change in a specific area is likely
- The current design resists safe modification (high coupling, fragile code)
- Extension points emerge from real requirements, not speculation
Defer OCP when:
- Requirements are stable or unclear
- The simpler solution is working fine
- You're guessing at future needs without stakeholder input
Think of it like buying storage containers: don't buy 50 containers "just in case" when you only need three today. Buy them when you actually have things to organize.
Key Takeaway: Apply the Open/Closed Principle based on real needs and evidence of change, not speculation—let YAGNI and KISS guide you away from premature abstraction.