الانتقال إلى المحتوى
Software ArchitectureSOLID· 7 دقائق للقراءة

Open/Closed Doesn't Mean You Never Edit Existing Code

Fix wrong code where it lives. Save the open/closed effort for the kinds of change that keep coming back.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

The shipping rule changes: orders of 500 or more now ship free. The team's guideline says OCP means existing classes are closed, so instead of editing ShippingPolicy, someone adds ShippingPolicyV2 and registers it for checkout. The nightly invoice job still creates the old ShippingPolicy directly, so for a week invoices charge 30 for shipping that checkout showed as free. Meanwhile, adding a wallet payment method meant editing the same switch in checkout, refunds and reports: the one place where OCP would actually have helped.

The common misconception

The belief: the means you should never modify a class once it's written. New behavior always goes into new classes: subclasses, decorators, V2s.

The wording invites it: "closed for modification" sounds absolute. Martin's own 1996 article said of a closed module: "The source code of such a module is inviolate. No one is allowed to make source code changes to it." His 2014 post states the essence as: "You should be able to extend the behavior of a system without having to modify that system." And Microsoft's architecture guide, in its section on single responsibility, says "Adding new classes is always safer than changing existing classes, since no code yet depends on the new classes."

The half-truth: code that lets you add an expected feature without touching working modules is valuable, and plugin systems prove it's possible. But that's a goal for specific kinds of change, not a ban on editing.

What actually happens

Meyer's "closed" meant stable and usable

Bertrand Meyer defined the principle in Object-Oriented Software Construction in 1988, and Martin's 2014 post quotes him. A module is open "if it is available for extension". It's closed when it "is available for use by other modules", which "assumes that the module has been given a well-defined, stable description". In other words, closed is about clients being able to rely on a module's interface. Craig Larman puts it precisely: a module "closed with respect to X" means clients are not affected if X changes.

Martin: "This doesn't mean you will never change the source code"

In 2013 someone on Twitter complained that OCP made little sense: presumably its fans barely use version control, since the only reason to change a source file would be bug fixes. Martin traced the confusion to his 1996 sound-bite, called it "a bit overstated", and pointed out that the same article says no significant program can be 100% closed and talks about strategic closure. Then he restated the principle: "This doesn't mean you will never change the source code, this doesn't mean you can stop using your version control systems (sheesh!)." The aim is that "when behavior changes in expected ways, you don't have to make sweeping changes to all the modules of the system", ideally "changing little or no old code".

Close against predicted variation, not everything

Larman argues that OCP is essentially the same as : "Identify points of predicted variation and create a stable interface around them." His advice is "You must pick your battles in design": apply it at the likely points of variation "but not others. Otherwise, effort is wasted and complexity may arise". He even notes that speculative future-proofing can cost more than reworking a simple design, and that intermediate developers tend toward overly flexible designs "in ways that never get used".

Wrong code is meant to be edited

Martin's 2020 summary of OCP explains what's actually protected: "When requirements change only part of the existing code is wrong. Much of the existing code is still right. And we want to make sure that we don't have to change the right code just to make the wrong code work again." A shipping rule that no longer matches the business is the wrong code. Wrapping it in a subclass keeps the wrong version alive.

The fix: edit the rule, close the real variation

C#
// "OCP says don't touch it", so the new rule became a subclasspublic class ShippingPolicy{    public virtual decimal Fee(decimal subtotal) => 30m;}public sealed class ShippingPolicyV2 : ShippingPolicy{    public override decimal Fee(decimal subtotal) =>        subtotal >= 500m ? 0m : base.Fee(subtotal);}// Meanwhile each new payment method edits switches like this one// in checkout, refunds and reportspublic static class Fees{    public static decimal Surcharge(string method, decimal total) =>        method switch        {            "card" => total * 0.02m,            "wallet" => 0m,            _ => throw new NotSupportedException(method),        };}

The shipping rule is now one class with one current rule, so every caller, including the invoice job, gets the change. Payment methods are different: the team has added several, and each one used to touch three switch statements. Behind IPaymentMethod, checkout, refunds and reports are closed with respect to new payment methods. Adding one still edits a line of old code, the registration in Program.cs, which is exactly Martin's "little or no old code".

MythReality
OCP means never edit existing codeMartin: it "doesn't mean you will never change the source code"
A changed rule belongs in a new subclassA rule that's no longer right is wrong code; edit it so every caller gets the fix
"Closed" means frozenMeyer: closed means available for use by other modules, with a stable, well-defined description
Every class should be open to every extensionNo significant program is 100% closed; Larman: pick your battles at predicted points of variation
OCP is about inheritanceLarman lists interfaces, polymorphism, indirection, and data- or rule-driven designs among its mechanisms

How to apply it in your project

  1. Fix wrong behavior in placeWhen a rule changes or a bug is found, edit the code that owns it, with a test that pins the new behavior. That's not an OCP violation.
  2. Find the variation that recursSearch the history for features of the same kind that each touched the same switch, if chain or type check in several places.
  3. Put a stable interface around that pointUse an interface and one class per variant, a lookup table, or rules read from configuration, so the next variant is mostly new code.
  4. Leave everything else simpleDon't add extension points for variations that haven't shown up. Revisit when a second or third change of the same kind arrives.

Key takeaways

  • OCP doesn't forbid editing code; Martin calls the "never touch it" reading an overstated sound-bite.
  • Meyer's "closed" means a module is stable and usable by others, so clients aren't disturbed.
  • Aim to add expected kinds of change with new code and little or no old code.
  • No program is fully closed: protect the points of predicted variation and pick your battles.
  • Wrong code is meant to be edited; wrapping it in V2 subclasses keeps the bug alive.

📚 المصادر

  1. An Open and Closed Case — Robert C. Martin, The Clean Code Blog (2013)
  2. The Open Closed Principle — Robert C. Martin, The Clean Code Blog (2014), quoting Bertrand Meyer's Object Oriented Software Construction (1988)
  3. Protected Variation: The Importance of Being Closed — Craig Larman, IEEE Software (2001)
  4. Solid Relevance — Robert C. Martin, The Clean Code Blog (2020)
  5. Architectural principles — .NET Architecture Guides, Microsoft Learn

التعليقات (0)