Course contentsShow
← Software Engineering
Lesson 206 of 1,9336. SOLID PrinciplesFree lesson

When to Apply OCP

Learn to identify variation points where future changes are likely and warrant OCP investment.

When to Apply OCP

What you'll learn: You'll learn how to identify the right situations where investing in the Open/Closed Principle actually pays off.


The Principle of Selective Investment

Not every piece of code needs OCP protection. Applying OCP everywhere creates unnecessary complexity, abstractions, and maintenance overhead. The key is identifying variation points—places in your code where change is likely or inevitable.

Think of it like earthquake-proofing buildings. You don't earthquake-proof every structure equally. A hospital in California? Absolutely critical. A garden shed in Vermont? Probably overkill. The investment should match the risk.

Identifying Worthy Variation Points

Apply OCP when you have evidence of likely change:

Business volatility: Pricing logic, tax calculations, shipping methods—anything tied to business rules that shift frequently or vary by region/customer.

External dependencies: Payment processors, notification services, data sources—things you don't control that might change or need alternatives.

Known variations: Multiple report formats, different authentication methods, various algorithm implementations—when you already know multiple versions exist or will exist.

Plugin/extension requirements: Features explicitly designed for third-party extension or configuration.

When NOT to Apply OCP

Stable, simple code: A date formatter used once that hasn't changed in years doesn't need abstraction layers.

Premature optimization: If you're just guessing about future change without evidence, you're probably over-engineering (remember YAGNI from earlier).

Low-impact changes: If modifications are rare, localized, and easy to test, the cost of abstraction may exceed its benefit.

Key Takeaway: Apply OCP strategically at proven or highly probable variation points—not everywhere. Let actual change drive your investment in flexibility.