open-closed-principle
Open/Closed Principle (OCP)
Overview
Software entities should be open for extension, but closed for modification.
When new functionality is needed, extend the system with new code rather than modifying existing code. If adding a feature requires changing existing if/else chains, you're violating OCP.
When to Use
- Adding a new payment method, notification channel, export format, etc.
- Tempted to add another
if/elseorswitchcase - Existing code works but needs new variants
- Feature request: "add support for X"
The Iron Rule
NEVER add another branch to an existing if/else or switch statement.
More from yanko-belov/code-craft
dont-repeat-yourself
Use when writing similar code in multiple places. Use when copy-pasting code. Use when making the same change in multiple locations.
84lazy-loading
Use when loading all data upfront. Use when initial page load is slow. Use when fetching data that might not be needed.
54keep-it-simple
Use when tempted to write clever code. Use when solution feels complex. Use when showing off skills instead of solving problems.
51separation-of-concerns
Use when component does too many things. Use when mixing data fetching, logic, and presentation. Use when code is hard to test.
44single-responsibility-principle
Use when creating or modifying classes, modules, or functions. Use when feeling pressure to add functionality to existing code. Use when class has multiple reasons to change.
39fail-fast
Use when handling errors. Use when tempted to catch and swallow exceptions. Use when returning default values to hide failures.
35