Skip to content

Open–Closed Principle (OCP) ​

"Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification." — Robert C. Martin, The Open-Closed Principle, Engineering Notebook, The C++ Report, 1996 (after Bertrand Meyer, 1988)

Summary: OCP says that for the kinds of change you expect, new behaviour should arrive as new code plugged into a stable abstraction, not as edits to code that already works. Focus: Meyer's 1988 definition and Martin's 1996 and 2014 glosses, abstraction at the point of variation, strategic closure, plugin architectures, Go interfaces, embedding, generics and registries, Laravel contracts, container and Manager::extend, feature flags, events, API compatibility, Protected Variations and the Expression Problem. Learning goal: Find the axis along which a module really varies, close it with the smallest abstraction that works (and not before the variation is real), and recognise when an "extension point" is speculative generality.

This page is the complete reference for the second SOLID principle: where it came from (Meyer's modules, Martin's C++ columns, his 2014 plugin argument, Larman's Protected Variations), every mechanism that implements it in Go and Laravel and in Java, .NET, TypeScript and Python, how the Go standard library and Laravel's own managers are built on it, when an abstraction pays for itself, and what OCP means for public APIs, schemas and events. Neighbours hold the rest: Single Responsibility decides where the module borders are; Liskov Substitution is the fine print that makes a plug-in safe; Interface Segregation keeps the abstraction small; Dependency Inversion makes the arrows point at it. The overview is on SOLID.

Page map ​

If you are looking forGo to
The principle in a few tablesEverything in one minute
Why it exists, the trade-off, the analogyWhy OCP exists
Meyer 1988, Martin 1996 and 2014, Larman 2001, Wadler 1998Where it comes from
Open/closed, point of variation, strategic closure, plugins, flags, events, APIs, Protected Variations, Expression ProblemThe concepts, one by one
Go, Laravel, Spring, .NET, TypeScript, Python mechanismsPer-language and per-framework view
Registries, init(), Manager, container tags, dispatch tablesMechanics
Before/after codeGo, Laravel
Growing switch, payment gateways, new storage driver, new event consumerSolving the classic problems
When to abstract (rule of three)Choosing
Plugins, events and versioned APIs across servicesIn architecture
A kata with before/after numbersLab: refactoring kata
Wrong beliefs, cheat sheet, self-check, every termMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The ideas.

TermIn plain wordsTiny exampleWhat goes wrong without it
Open for extensionYou can add new behaviourA new discount typeEvery feature edits old code
Closed for modificationWorking code is not edited for that changeFinalPriceCents untouchedRetest of everything already working
Point of variationThe exact place where variants differ"how a discount is computed"Abstractions in the wrong place
Strategic closureChoose which changes to be closed againstClose against new gateways, not new currenciesAbstract-everything bloat
Plugin architectureCore knows an interface; plugins registerdatabase/sql driversCore imports every vendor
Protected VariationsStable interface around a predicted changeLarman's name for OCPChange at one point ripples out
Speculative generalityExtension points nobody usesPaymentStrategyFactoryInterface with one implementationCost with no benefit
Expression ProblemAdding cases vs adding operationsNew shape vs new Perimeter()Each design is closed on one axis only

The mechanisms.

MechanismGoLaravelClosed partOpen part
Interface + new typetype Discount interface{...}interface PaymentGatewayThe callerThe implementations
Registrysql.Register, image.RegisterFormatCache::extend, Storage::extend, Auth::extendThe core package / managerThe drivers
Container(manual wiring in main)bind, tag + giveTagged, #[Bind], #[BindWhen]The consumer classThe bound implementation
EventsChannels, callbacksEvents + listenersThe publisherThe subscribers
CompositionStruct embedding, middleware func(http.Handler) http.HandlerMiddleware, decoratorsThe wrapped typeThe wrapper
Genericsfunc Validate[T any](v T, rules ...Rule[T])(PHP has no generics; PHPStan templates)The algorithmThe element types and rules
Data / tableMap of handlersConfig arrays, database rowsThe engineThe rows

Three things to do.

SituationDo this
A switch on a type code grows every sprintReplace it with an interface at that point, one type per case
Another team or package must add variantsGive them a registry (Register/extend) so they never edit your code
You think you might need variants one dayWrite the direct code; abstract on the third real variant

Why OCP exists ​

Every edit to working code risks breaking it and forces a retest of everything that depends on it. Martin's 1996 example is a DrawAllShapes function with a switch on a shape type code: to add a triangle you open DrawAllShapes, add a case, and retest circles and squares that had nothing to do with triangles. Multiply that by every switch on the same type code across the program and adding a shape becomes a hunt. OCP asks you to arrange the code so that the expected kinds of change become additions: a new type, a new file, a new package, a new registered driver.

Modify in place (closed nowhere)Extend through an abstraction (closed where it matters)
Simple to read: everything in one switchOne more level of indirection to follow
Every new variant edits the same functionNew variant = new file; old code untouched
All variants retested on each changeOnly the new variant needs new tests
One team owns all variantsOther teams and packages can add variants
Fast inner loops (no dynamic dispatch)Dynamic dispatch can cost in hot paths
Right for one or two stable variantsRight for open-ended, frequently growing sets

The analogy we reuse on this page: a wall socket. The socket is closed: nobody rewires the house to plug in a lamp. It is open: any device that fits the plug standard works, including devices invented decades after the house was built. The plug standard is the abstraction; the electrician never met the engineer who designed your charger. Note what the socket is not closed against: a new voltage. Closure is always against a chosen kind of change.

Three common misunderstandings, up front ​

  1. "Never change existing code." Impossible, and Martin's 1996 column says so: "no significant program can be 100% closed." You choose what to be closed against.
  2. "Put an interface on everything, just in case." That is speculative generality. Abstractions have a cost; wait for real variants.
  3. "OCP needs inheritance." It needs an abstraction. Go uses interfaces, functions and registries; Laravel uses contracts, the container and managers.

Where it comes from ​

Meyer, 1988. Bertrand Meyer's Object-Oriented Software Construction stated it about modules. Quoted by Martin in his 2014 post: "A satisfactory modular decomposition technique must satisfy one more requirement: It should yield modules that are both open and closed." Meyer's "open" meant "available for extension. For example, it should be possible to add fields to the data structures it contains, or new elements to the set of functions it performs." His "closed" meant "available for use by other modules": compiled into a library, or a specification "approved by management". Meyer's mechanism was inheritance: a closed, published class is extended by subclassing it.

Martin, 1996. The first Engineering Notebook column in The C++ Report takes Meyer's wording and moves the mechanism from implementation inheritance to abstraction:

"It is possible for a module to manipulate an abstraction. Such a module can be closed for modification since it depends upon an abstraction that is fixed. Yet the behavior of that module can be extended by creating new derivatives of the abstraction." — Robert C. Martin, The Open-Closed Principle, The C++ Report, 1996

The same column introduces strategic closure:

"Since closure cannot be complete, it must be strategic. That is, the designer must choose the kinds of changes against which to close his design." — Robert C. Martin, The Open-Closed Principle, The C++ Report, 1996

and derives familiar heuristics from OCP: make member variables private, avoid global variables, treat RTTI (dynamic_cast) as dangerous when it is used to switch on concrete types. His 2000 paper Design Principles and Design Patterns calls it "the most important" of the class design principles.

Martin, 2014. The blog post concedes that Meyer's framing "is obviously dated" (modules need not be compiled; "approved by management smacks of a waterfall mentality") and restates it:

"You should be able to extend the behavior of a system without having to modify that system." — Robert C. Martin, The Open Closed Principle, The Clean Code Blog, 12 May 2014

and names its strongest form:

"Plugin systems are the ultimate consummation, the apotheosis, of the Open-Closed Principle." — Robert C. Martin, The Open Closed Principle, 2014

Larman, 2001. In Protected Variation: The Importance of Being Closed (IEEE Software, May/June 2001), Craig Larman argued that OCP and Alistair Cockburn's Protected Variation pattern are the same principle and that both are what Parnas meant by information hiding:

"Identify points of predicted variation and create a stable interface around them." — Craig Larman, Protected Variation: The Importance of Being Closed, IEEE Software, 2001

Wadler, 1998. Philip Wadler's email naming the Expression Problem shows why no design is closed on every axis:

"The goal is to define a datatype by cases, where one can add new cases to the datatype and new functions over the datatype, without recompiling existing code, and while retaining static type safety" — Philip Wadler, The Expression Problem, email, 12 November 1998

The concepts, one by one ​

Open and closed: Meyer's two halves Must-know ​

In plain words: "closed" means other code already relies on this module, so you do not edit it; "open" means you can still make it do new things.

Common misunderstanding: "Closed means frozen forever." Meyer's closed means published and depended upon; you still fix bugs in it. What you avoid is editing it for each new feature along an axis you expected.

Definition: a module is closed with respect to a kind of change X when clients are not affected if X changes (Larman: the phrase "closed with respect to X" "means that clients are not affected if X changes"). It is open with respect to X when X can be added by new code.

text
     Request                       Closed module (FinalPriceCents)      New code
1    "add VIP 20% discount"        untouched                            vip.go: type VIPPercent
2    "add Black Friday flat 10€"   untouched                            blackfriday.go
3    "prices now in two currencies" EDITED (not closed against this)   -- an unexpected axis --

Real scenario: a pricing engine closed against new discount kinds; a notifier closed against new channels; a report exporter closed against new formats; Laravel's cache closed against new stores.

Fix: decide the axis explicitly (write it in a comment above the interface: "varies by: discount kind").

Abstraction at the point of variation Must-know ​

In plain words: put the interface exactly where the variants differ, and nowhere else.

Common misunderstanding: "Abstract the whole service." An interface around the entire PaymentService lets you swap the service, but adding a gateway still means editing the one implementation. The variation is how one gateway charges, so that is where the interface goes.

Definition: the point of variation is the smallest unit of behaviour that differs between variants. The abstraction is sized to it (often one method; Go's proverb "The bigger the interface, the weaker the abstraction" applies), owned by the caller, and named after the role.

text
     Code path                                     Varies?   Abstraction?
1    load order, check status                      no        none
2    compute discount                              YES       Discount.Apply(order, price)
3    clamp to zero, round                          no        none
4    persist, publish event                        no        (other principles)

Fix: extract only line 2 behind an interface; see the Go before/after.

Strategic closure Must-know ​

In plain words: you cannot be closed against everything, so pick the changes that are likely and close against those.

Common misunderstanding: "A good design anticipates all change." Martin: "no significant program can be 100% closed" and "there will always be some kind of change against which it is not closed."

Definition: strategic closure is the choice of axes of change against which a module is closed, based on experience and evidence. Martin's 1996 column shows two techniques: an ordering abstraction (so DrawAllShapes is closed against draw-order changes) and a data-driven approach (a table of type priorities), so that the ordering policy lives in data instead of code.

text
     Evidence                                   Decision
1    3 discount kinds added in 6 months         close against "new discount kind"
2    0 currency changes in 5 years              do not abstract currency
3    2 payment gateways, 3rd one in roadmap     close against "new gateway"
4    1 PDF library, never changed               call it directly

Fix (data-driven closure in SQL): when the variants are data (rates, thresholds, priorities), a table is the cheapest extension point: new variants are INSERTs, not deployments.

sql
CREATE TABLE discount_rules (
  id          BIGSERIAL PRIMARY KEY,
  kind        TEXT NOT NULL CHECK (kind IN ('percent', 'flat')),
  coupon      TEXT,
  min_cents   BIGINT NOT NULL DEFAULT 0,
  value       BIGINT NOT NULL,
  priority    INT NOT NULL DEFAULT 100,
  active_from TIMESTAMPTZ NOT NULL DEFAULT now(),
  active_to   TIMESTAMPTZ
);
-- Black Friday is an INSERT, not a code change:
INSERT INTO discount_rules (kind, min_cents, value, priority, active_from, active_to)
VALUES ('flat', 5000, 1000, 10, '2026-11-27', '2026-11-30');

The code stays closed against new rows; it is open to new kinds only through a code change, which is the right place for logic.

Plugin architecture Must-know ​

In plain words: the core defines an interface and a way to register implementations; plugins import the core, never the other way round.

Common misunderstanding: "Plugins need dynamic loading (DLLs, .so)." The OCP property is about source dependencies, not loading. database/sql drivers are compiled in, yet the core never imports them.

Definition: Martin 2014: "the way you get a plugin architecture is to make sure that all dependencies inside the plugin, point at the system; and that nothing in the system points out towards the plugins. The system doesn't know about the plugins. The plugins know about the system."

Closed coredatabase/sql · CacheManagerdriver.Driver(interface)Register(name)extend(name)PostgreSQL driverpgx/v5/stdlibMySQL drivergo-sql-driver/mysqlSQLite drivermodernc.org/sqliteNew drivernew package, no core editComposition rootmain: blank importsLaravel: service providerThe core never imports a driver.Drivers import the core and register.

The diagram shows the shape shared by Go's database/sql and Laravel's cache manager: the closed core owns the interface and the registry; drivers point inward and register; only the composition root (main in Go, a service provider in Laravel) names the drivers.

text
     Step   Go (database/sql)                                  Laravel (cache)
1    boot   import _ "github.com/jackc/pgx/v5/stdlib"          AppServiceProvider::register()
2           driver's init() calls sql.Register("pgx", ...)     Cache::extend('mongo', fn () => ...)
3    use    sql.Open("pgx", dsn)                               Cache::store('mongo')->get('k')
4           core looks up the name, calls the driver           CacheManager looks up the creator

Real scenario: database/sql (PostgreSQL via pgx, MySQL via go-sql-driver, SQLite, SQL Server, Oracle, CockroachDB speaking the PostgreSQL wire protocol), image.Decode with image/png, image/jpeg, image/gif registering formats, Laravel cache/filesystem/auth drivers, Terraform providers, editor extensions.

Extension mechanisms in Go: interfaces, embedding, generics Important ​

In plain words: Go gives you three ways to add behaviour without editing: a new type that satisfies an interface, a struct that embeds another and adds or wraps methods, and generic functions that work for new types.

Common misunderstanding: "Embedding is inheritance, so it lets me override methods of the inner type." It does not: Cheney's talk shows that the embedded type's method set "cannot be altered by embedding". Calls inside the inner type still go to the inner type's methods. The outer type can only add or shadow at its own level, which is exactly "closed for modification, open for extension".

Definition:

MechanismWhat stays closedWhat is openTypical stdlib example
Implicit interfaceThe function taking the interfaceAny type with the methodsio.Reader, http.Handler, sort.Interface
Function typeThe callerAny function of that signaturehttp.HandlerFunc, middleware
EmbeddingThe embedded typeThe outer type's added/wrapped methodsbufio.ReadWriter embeds *Reader and *Writer
GenericsThe algorithmElement types (and rule types)slices.SortFunc, maps.Keys
Registry + init()The core packageRegistered driverssql.Register, image.RegisterFormat
go
// Package generics shows two more Go extension points: type parameters and
// struct embedding.
package generics

import (
	"context"
	"fmt"
	"log/slog"
)

// Rule is a validation rule over any type. Validate[T] is written once and is
// closed; new rules are new types.
type Rule[T any] interface {
	Check(v T) error
}

// RuleFunc lets a plain function act as a Rule, like http.HandlerFunc.
type RuleFunc[T any] func(T) error

func (f RuleFunc[T]) Check(v T) error { return f(v) }

func Validate[T any](v T, rules ...Rule[T]) error {
	for _, r := range rules {
		if err := r.Check(v); err != nil {
			return err
		}
	}
	return nil
}

type Signup struct{ Email, Country string }

var NotEmpty = RuleFunc[Signup](func(s Signup) error {
	if s.Email == "" {
		return fmt.Errorf("email is required")
	}
	return nil
})

// --- Embedding: extend a type without editing it. ---

type Store interface {
	Get(ctx context.Context, key string) (string, error)
}

// LoggingStore embeds a Store: every method of the inner store is promoted,
// and Get is wrapped. The inner type's own methods are not altered.
type LoggingStore struct {
	Store
	Log *slog.Logger
}

func (l LoggingStore) Get(ctx context.Context, key string) (string, error) {
	v, err := l.Store.Get(ctx, key)
	l.Log.InfoContext(ctx, "store get", "key", key, "err", err)
	return v, err
}

Extension mechanisms in Laravel: contracts, container, Manager::extend Important ​

In plain words: Laravel code depends on contracts (interfaces); the container decides which implementation to inject; managers let anyone add a named driver with extend().

Common misunderstanding: "Facades make Laravel code closed to change." A facade such as Cache is a static proxy to a container service, so the implementation behind it is still swappable (Cache::extend, Cache::fake-style test doubles, container bindings).

Definition: Laravel's docs call contracts "a set of interfaces that define the core services provided by the framework". The container resolves them (bind, singleton, contextual when()->needs()->give(), tag() + giveTagged(), and attributes #[Bind], #[Singleton], #[BindWhen], #[Tag]). Illuminate\Support\Manager provides driver($name), extend($driver, Closure $callback) and create{Name}Driver methods; Cache, Filesystem and Auth document their own extend().

php
// Open: a new report is a new class plus one tag line. Closed: ReportAggregator.
$this->app->tag([CpuReport::class, MemoryReport::class, DiskReport::class], 'reports');

$this->app->when(ReportAggregator::class)
    ->needs('$reports')
    ->giveTagged('reports');

final class ReportAggregator
{
    public function __construct(private iterable $reports) {} // never edited again
}

Feature flags vs OCP Important ​

In plain words: a feature flag is an if you can flip at runtime; OCP is a structure that lets you add variants without editing. Flags are for temporary variation; OCP is for permanent, growing variation.

Common misunderstanding: "Flags make code open for extension." Each flag is a modification of the code it lives in, and a release toggle that is never removed becomes a permanent switch. Pete Hodgson's Feature Toggles article (on martinfowler.com) separates release, experiment, ops and permissioning toggles and recommends managing their "carrying cost".

Definition: a feature flag selects a code path at runtime from configuration or user context. A good flag decides which implementation is used at one point (Hodgson's "Inversion of Decision"), so the toggle point is a single binding, not if statements scattered through the code.

php
// Laravel 13: the flag picks the implementation in ONE place (the container),
// so callers stay closed. #[BindWhen] is documented on the container page.
#[Bind(RedisEventPusher::class)]
#[BindWhen(BetaEventPusher::class, static fn () => Feature::active('beta-events'))]
interface EventPusher
{
    public function push(string $event, array $payload): void;
}
Feature flagOCP extension point
LifetimeDays to weeks (release toggles)Years
Number of variantsUsually 2 (on/off)Open-ended
Who adds variantsThe same teamOther teams, packages, plugins
CleanupMust be deletedStays
Best combinedFlag selects which registered implementation is bound

Event-driven extension Important ​

In plain words: the publisher announces "this happened"; anyone can react. Adding a reaction does not edit the publisher.

Common misunderstanding: "Events remove all coupling." They remove the publisher's dependency on subscribers, but subscribers now depend on the event's shape: the event schema is the new closed abstraction and must evolve compatibly.

Definition: event-driven extension makes the publisher closed against new consumers. In Laravel, OrderPlaced::dispatch($order) with listeners found by event discovery; in Go, a list of callbacks or a broker topic. Across services, see Event-Driven Architecture and Message Design & Schema Evolution.

text
     Time   Publisher (checkout)               Subscribers
1    M1     publish OrderPlaced{v1}            SendInvoice
2    M4     unchanged                          + AwardLoyaltyPoints (new listener, new deploy)
3    M7     unchanged                          + FraudScore (new service subscribes to the topic)
4    M9     add optional field giftWrap        old subscribers ignore it (additive = compatible)

Speculative generality and the rule of three Must-know ​

In plain words: an abstraction nobody needs yet is a cost with no benefit. Wait until you have real variants.

Common misunderstanding: "OCP says to design every class for extension." Martin's own 1996 column says closure must be strategic, and Dan North's 2021 critique of OCP ("Write simple code that is easy to change") lands in the same place: code that is easy to change does not need speculative hooks.

Definition: speculative generality is the code smell in Fowler's Refactoring for hooks, parameters and abstract classes added "in case we need it". The rule of three (also from Refactoring, where Fowler credits it to Don Roberts; book not read here, paraphrased from common usage) says: the first time, just do it; the second time, wince and duplicate; the third time, refactor. Applied to OCP: abstract when the third variant arrives, or when the second variant comes from someone else (another team, a package).

Sign of speculative generalityExampleFix
Interface with one implementation and no test doublePdfRendererInterface → DomPdfRenderer onlyInline the interface
Factory that builds one thingGatewayFactory::make('stripe') with no other branchCall the constructor
Unused parameters "for later"charge(Order $o, array $options = []) never usedRemove the parameter
Abstract base class with one childAbstractExporter → CsvExporterCollapse Hierarchy

The full smell catalogue, with the moves that remove each smell, is the chapter Code Smells, Anti-Patterns & Refactoring.

A new variant is requestedFirst variant ever?yes: left · no: downWrite it directlyno interface yetSecond variant?yes: left · temporary: rightSmall switch is finename the axis in a commentFeature flagshort-lived, then deleteThird variant, or added byanother team / package?Interface at the point of variationregistry, Manager::extend, tagged bindingsPublished API / event?only add; version to break

The flow above is the practical rule: write the first variant directly, tolerate a small switch for the second, introduce an interface at the point of variation for the third (or as soon as another team adds variants), use a feature flag for short-lived variation, and for a published API or event only ever add.

OCP in APIs, schemas and contracts Important ​

In plain words: a published API is the most closed module you own, because you cannot edit its clients. So you only ever add: new optional fields, new endpoints, new event types. Breaking changes go into a new version.

Common misunderstanding: "Adding a field is always safe." Adding an optional response field is; adding a required request field, renaming, narrowing a type or changing meaning is a modification that breaks clients.

Definition: backward-compatible evolution is OCP applied to contracts: the existing contract is closed, the set of capabilities is open. A behaviour change under the same name is the contract-level version of an LSP violation: the database world has a famous example, where "Repeatable Read" names different promises in PostgreSQL and MySQL InnoDB (see Isolation Levels); clients that swap one for the other break although the name did not change.

sql
-- Expand/contract: closed for existing readers, open for the new feature.
ALTER TABLE orders ADD COLUMN gift_wrap BOOLEAN NOT NULL DEFAULT false;  -- additive, old code unaffected
-- new code writes gift_wrap; old code ignores it; no existing query changes meaning
-- a breaking change (rename, type change) goes through a new column + backfill + later drop
ChangeCompatible?OCP reading
Add optional response fieldYesExtension
Add new endpoint / event typeYesExtension
Add enum value consumers switch onRiskyConsumers' switch is not closed
Make optional request field requiredNoModification
Rename or retype a fieldNoModification: new version

Protected Variations (GRASP) Good to know ​

In plain words: the same idea as OCP under a clearer name: protect the rest of the system from a part you expect to vary by wrapping it in a stable interface.

Common misunderstanding: "Protected Variations is only about object design." Larman: PV "applies to everything from the largest architectural concerns to the smallest coding decision" (data-driven designs, service lookup, interpreters, the Uniform Access Principle, standard protocols).

Definition: Protected Variations is one of the GRASP principles in Larman's Applying UML and Patterns. Its IEEE Software column states "OCP and PV are two expressions of the same principle" and nominates "protected variation" as the general term.

The Expression Problem Good to know ​

In plain words: object-style code is open to new types but closed to new operations; switch-style code is the reverse. You choose which axis to keep open.

Common misunderstanding: "Interfaces make code open in every direction." Add a Perimeter() method to the Shape interface and every implementation must change: that axis is not closed.

Definition: Wadler's 1998 framing: add new cases and new functions "without recompiling existing code, and while retaining static type safety". Mainstream languages give you one axis cheaply.

DesignNew case (type)New operationLanguages and tools
Interface / class per caseCheap: new typeExpensive: edit every typeGo interfaces, PHP interfaces, Java/C# classes
switch / pattern match over a closed setExpensive: edit every switchCheap: new functionGo type switch, PHP match, TS discriminated unions with exhaustiveness checks
VisitorExpensiveCheapGoF Visitor
Open dispatchCheapCheap (with limits)Python functools.singledispatch, Clojure multimethods

This is also the honest version of Casey Muratori's 2023 "Clean" Code, Horrible Performance argument: the switch-based shape version was about 1.5× faster than the polymorphic one in his C++ measurement, because a closed set of cases lets the compiler and the CPU do more. If your set of types is closed and hot, the switch may be the right design.

Per-language and per-framework view ​

Language / frameworkPrimary extension pointRegistry / discoveryComposition rootNote
GoSmall implicit interfaces, function typesRegister + init() + blank import (database/sql, image)mainEmbedding extends without altering the inner type; generics since Go 1.18
PHP / LaravelContracts (Illuminate\Contracts\*)Managers' extend(), container tag(), event discoveryService providers (bootstrap/providers.php)PSR-11 ContainerInterface (get, has) standardises containers across frameworks
Java / SpringInterfaces, abstract classesSpring autowires "arrays and typed collections" of all candidate beans; JDK ServiceLoader@Configuration classesInject List<DiscountRule> and a new @Component joins automatically
C# / .NETInterfacesMicrosoft.Extensions.DependencyInjection; keyed services (GetKeyedServices)Program.cs / IServiceCollectionMultiple registrations of one interface resolve as a sequence
TypeScriptStructural interfaces ("type compatibility in TypeScript is based on structural subtyping")Plugin arrays in config (bundlers, linters)App bootstrapDiscriminated unions are the "closed set" side of the Expression Problem
PythonDuck typing, typing.Protocol, ABCsPackage entry points via importlib.metadata.entry_points(); functools.singledispatchModule that builds the appEntry points are how pytest and other tools discover plugins

Mechanics ​

Registry with init() (Go) Must-know ​

The Go documentation for database/sql: "Register makes a database driver available by the provided name. If Register is called twice with the same name or if driver is nil, it panics." image.RegisterFormat "registers an image format for use by Decode", identified by a name and a magic prefix. The pattern, rebuilt for notifications:

go
// Package notify is closed for modification and open for extension, in the
// same shape as database/sql: drivers register themselves by name.
package notify

import (
	"context"
	"fmt"
	"sort"
	"sync"
)

type Message struct {
	To, Body string
}

// Driver is the point of variation. Implementations must be safe for
// concurrent use and must not mutate the Message.
type Driver interface {
	Send(ctx context.Context, m Message) error
}

var (
	mu      sync.RWMutex
	drivers = map[string]Driver{}
)

// Register makes a driver available by name. Like sql.Register it panics on
// a nil driver or a duplicate name, because both are programming errors.
func Register(name string, d Driver) {
	mu.Lock()
	defer mu.Unlock()
	if d == nil {
		panic("notify: Register driver is nil")
	}
	if _, dup := drivers[name]; dup {
		panic("notify: Register called twice for driver " + name)
	}
	drivers[name] = d
}

// Drivers returns the sorted list of registered names.
func Drivers() []string {
	mu.RLock()
	defer mu.RUnlock()
	names := make([]string, 0, len(drivers))
	for n := range drivers {
		names = append(names, n)
	}
	sort.Strings(names)
	return names
}

// Send never changes when a channel is added.
func Send(ctx context.Context, channel string, m Message) error {
	mu.RLock()
	d, ok := drivers[channel]
	mu.RUnlock()
	if !ok {
		return fmt.Errorf("notify: unknown driver %q (forgotten import?)", channel)
	}
	return d.Send(ctx, m)
}
go
// Package sms is another extension. notify does not import it; it imports notify.
package sms

import (
	"context"
	"fmt"

	"academy/solid/ocp/registry/notify"
)

type driver struct{ sender string }

func (d driver) Send(_ context.Context, m notify.Message) error {
	fmt.Printf("SMS from %s to %s: %s\n", d.sender, m.To, m.Body)
	return nil
}

func init() { notify.Register("sms", driver{sender: "ACME"}) }
go
// Package app is the composition root: the only place that names the
// extensions, through blank imports, exactly like importing a SQL driver.
package app

import (
	"context"

	_ "academy/solid/ocp/registry/email"
	"academy/solid/ocp/registry/notify"
	_ "academy/solid/ocp/registry/sms"
)

func Welcome(ctx context.Context, channel, to string) error {
	return notify.Send(ctx, channel, notify.Message{To: to, Body: "Welcome!"})
}

Knobs and failure modes:

DetailBehaviourWhy
Duplicate namepanic (as sql.Register)Two drivers claiming one name is a programming error; fail at start-up
Nil driverpanicSame
Unknown name at useReturned error (sql: unknown driver "x" (forgotten import?) in database/sql)The usual cause is a missing blank import
ConcurrencyRegistry guarded by sync.RWMutexinit() order is per package; lookups may run concurrently
DiscoverabilityDrivers() returns sorted namesDebugging and health endpoints
Hidden dependencyBlank imports in mainKeep them in the composition root only

Manager::extend (Laravel) Must-know ​

Illuminate\Support\Manager::driver($driver = null) resolves a name: if a custom creator was registered with extend($driver, Closure $callback) it is called; otherwise the manager calls create{StudlyName}Driver(). Resolved drivers are cached per manager instance, which is why a manager used with extend() should be a singleton (the snippet below uses #[Singleton]). The framework's own extension points, from the Laravel 13 docs:

SubsystemExtension callWhere to register
CacheCache::extend('mongo', fn (Application $app) => Cache::repository(new MongoStore))In register() inside $this->app->booting(...), as the docs show
FilesystemStorage::extend('dropbox', fn (Application $app, array $config) => new FilesystemAdapter(...))boot()
Auth guardsAuth::extend('jwt', fn (Application $app, string $name, array $config) => new JwtGuard(...))boot()
Auth user providersAuth::provider('mongo', fn (Application $app, array $config) => new MongoUserProvider(...))boot()
Your ownPaymentManager extends Manager + extend('zarinpal', ...)Any provider's boot()

Dispatch tables and data-driven closure Good to know ​

A map[string]Handler in Go or an array of class names in a Laravel config file is a registry without the ceremony. Martin's 1996 column calls this the "data driven" approach to closure. It is closed against new entries but not against new behaviour shapes.

go
var exporters = map[string]func(io.Writer, []Row) error{
	"csv":  writeCSV,
	"json": writeJSON,
	// new format: one line here and one new function; Export never changes
}

func Export(w io.Writer, format string, rows []Row) error {
	f, ok := exporters[format]
	if !ok {
		return fmt.Errorf("export: unknown format %q", format)
	}
	return f(w, rows)
}

Go ​

Before ​

A pricing function with a switch over discount types. Every new promotion is an edit here, and a retest of every branch already present.

go
package before

type Order struct {
	SubtotalCents int64
	Customer      string
	Coupon        string
}

// Every new kind of discount forces an edit to this function,
// and a retest of every branch already in it.
func FinalPriceCents(o Order) int64 {
	price := o.SubtotalCents
	switch {
	case o.Coupon == "WELCOME10":
		price -= price / 10
	case o.Customer == "vip":
		price -= price / 5
	case o.SubtotalCents > 500_00:
		price -= 20_00
	}
	if price < 0 {
		return 0
	}
	return price
}

After ​

Discount is the fixed abstraction. The pricing function depends on it and is now closed. Each new promotion is a new type in a new file.

go
package after

type Order struct {
	SubtotalCents int64
	Customer      string
	Coupon        string
}

// Discount is the fixed abstraction. The pricing engine depends on it
// and nothing else, so the engine is closed for modification.
type Discount interface {
	// Apply returns the amount to subtract, in cents. It must not be negative.
	Apply(o Order, priceCents int64) int64
}

// FinalPriceCents never changes again. Behaviour is extended by passing new Discounts.
func FinalPriceCents(o Order, discounts ...Discount) int64 {
	price := o.SubtotalCents
	for _, d := range discounts {
		price -= d.Apply(o, price)
	}
	if price < 0 {
		return 0
	}
	return price
}

// --- Extensions. Each one is a new file, not an edit. ---

type CouponPercent struct {
	Code    string
	Percent int64
}

func (c CouponPercent) Apply(o Order, price int64) int64 {
	if o.Coupon != c.Code {
		return 0
	}
	return price * c.Percent / 100
}

type VIPPercent struct{ Percent int64 }

func (v VIPPercent) Apply(o Order, price int64) int64 {
	if o.Customer != "vip" {
		return 0
	}
	return price * v.Percent / 100
}

type BigBasketFlat struct{ ThresholdCents, OffCents int64 }

func (b BigBasketFlat) Apply(o Order, price int64) int64 {
	if o.SubtotalCents <= b.ThresholdCents {
		return 0
	}
	return b.OffCents
}

The Go angle ​

Cheney maps OCP onto embedding ("embedding is a powerful tool which allows Go's types to be open for extension"), but the everyday Go mechanism is the one above: a small interface at the point of variation, satisfied implicitly by any new type, owned by the consumer. The standard library is full of closed cores: net/http is closed against new handlers (http.Handler), io.Copy against new readers and writers, database/sql against new databases, image against new formats, encoding/json against new types (json.Marshaler). Middleware (func(http.Handler) http.Handler) extends a handler without editing it.

Laravel ​

Before ​

A payment service with a switch over gateway names. Adding Zarinpal means opening a class that already handles Stripe and the wallet correctly.

php
<?php

namespace App\Services;

use App\Models\Order;
use RuntimeException;

// Adding a fourth gateway means opening this class, adding a case,
// and re-testing the three cases that already worked.
class PaymentService
{
    public function charge(Order $order, string $gateway): string
    {
        switch ($gateway) {
            case 'stripe':
                $client = new \Stripe\StripeClient(config('services.stripe.secret'));
                $intent = $client->paymentIntents->create([
                    'amount' => $order->total_cents, 'currency' => 'usd',
                ]);

                return $intent->id;

            case 'zarinpal':
                $response = \Illuminate\Support\Facades\Http::post(
                    'https://api.zarinpal.com/pg/v4/payment/request.json',
                    ['amount' => $order->total_cents, 'merchant_id' => config('services.zarinpal.id')]
                );

                return $response->json('data.authority');

            case 'wallet':
                $order->user->decrement('wallet_cents', $order->total_cents);

                return 'wallet-'.$order->id;

            default:
                throw new RuntimeException("Unknown gateway {$gateway}");
        }
    }
}

After ​

A PaymentGateway contract and a Manager. Drivers are created by create{Name}Driver methods or registered from outside with extend(). A second team, or a third-party package, can add a gateway without touching PaymentManager.

php
<?php

// app/Contracts/PaymentGateway.php — the fixed abstraction.
namespace App\Contracts;

use App\Models\Order;

interface PaymentGateway
{
    /** Charge the order and return a provider reference. */
    public function charge(Order $order): string;
}

// app/Payments/PaymentManager.php — closed for modification.
// New gateways are registered with extend(); this class never changes.
namespace App\Payments;

use App\Contracts\PaymentGateway;
use Illuminate\Container\Attributes\Singleton;
use Illuminate\Support\Manager;

// One shared instance, so drivers registered with extend() are seen by every consumer.
#[Singleton]
class PaymentManager extends Manager
{
    public function getDefaultDriver(): string
    {
        return $this->config->get('payments.default');
    }

    protected function createStripeDriver(): PaymentGateway
    {
        return new StripeGateway($this->config->get('services.stripe.secret'));
    }

    protected function createWalletDriver(): PaymentGateway
    {
        return new WalletGateway();
    }
}

// app/Payments/StripeGateway.php — one extension, one file.
namespace App\Payments;

use App\Contracts\PaymentGateway;
use App\Models\Order;

final class StripeGateway implements PaymentGateway
{
    public function __construct(private string $secret) {}

    public function charge(Order $order): string
    {
        $client = new \Stripe\StripeClient($this->secret);

        return $client->paymentIntents->create([
            'amount' => $order->total_cents, 'currency' => 'usd',
        ])->id;
    }
}

// A third party, or another team, adds Zarinpal without touching PaymentManager:
// in a service provider's boot():
//
//   $this->app->make(PaymentManager::class)->extend('zarinpal', fn () => new ZarinpalGateway(
//       config('services.zarinpal.id')
//   ));

// app/Services/PaymentService.php — depends only on the abstraction.
namespace App\Services;

use App\Models\Order;
use App\Payments\PaymentManager;

final class PaymentService
{
    public function __construct(private PaymentManager $gateways) {}

    public function charge(Order $order, ?string $gateway = null): string
    {
        return $this->gateways->driver($gateway)->charge($order);
    }
}

The Laravel angle ​

Laravel is built on OCP. Its service providers are "the central place of all Laravel application bootstrapping" (Laravel 13 docs), which makes them the composition root where extensions are registered. Cache, filesystem, auth, queue, mail and broadcasting are managers whose sets of drivers are open. Events and listeners keep publishers closed against new reactions. The container's tags and contextual bindings let a consumer receive "all reports" or "the S3 disk" without naming them.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Growing switch on a type codeReplace Conditional with PolymorphismInterface at the point of variation, one type per caseNew case = new fileIndirection; Expression Problem trade-off
Another team must add variantsRegistry / Manager::extendRegister(name, impl) / extend('name', fn)No edits to the core, no merge conflictsName collisions, hidden blank imports
Variants are values, not logicData-driven closureTable or config rowsNew variant without deployNot for new behaviour
New reactions to a business factEventsOrderPlaced + listeners / topicPublisher closedEvent schema becomes the contract
Optional cross-cutting behaviourDecorator / middleware / embeddingWrap, do not editComposableOrder of wrappers matters
Temporary variationFeature flag at one binding#[BindWhen], PennantSafe rolloutMust be deleted

New storage driver without touching the core ​

php
// app/Providers/AppServiceProvider.php
public function register(): void
{
    $this->app->booting(function () {
        Cache::extend('mongo', fn (Application $app) => Cache::repository(new MongoStore));
    });
}
// config/cache.php: 'stores' => ['mongo' => ['driver' => 'mongo']]
// Cache::store('mongo')->put('k', 'v', 60);  -- CacheManager was never edited

New event consumer without touching the publisher ​

php
// app/Listeners/AwardLoyaltyPoints.php: discovered automatically; PlaceOrder is unchanged.
final class AwardLoyaltyPoints implements ShouldQueue
{
    public function handle(OrderPlaced $event): void
    {
        $event->order->user->increment('points', intdiv($event->order->total_cents, 100));
    }
}

Choosing: when to abstract ​

SituationRecommendationExtra techniqueReason
One variant, no roadmap for moreDirect codeNoneSpeculative generality costs now, pays never
Second variant arrivesSmall switch or ifName the axis in a commentRule of three: not enough evidence yet
Third variant, or a variant from another teamInterface at the point of variationRegistry / extend / tagged bindingsThe axis is real
Variants differ only in numbersTable or configAdmin UI over the tableData-driven closure
Short-lived variation (A/B, rollout)Feature flagFlag selects a bindingMust be removed later
New reactions to a factDomain eventsQueue listeners, outbox across servicesPublisher closed against consumers
Public API / event schemaAdditive changes onlyVersion for breaking changesClients cannot be edited
Hot loop over a closed set of typesswitchBenchmarkDispatch cost; Expression Problem trade-off
Framework extensionUse the framework's hookCache::extend, sql.RegisterNever fork the framework

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

How it shows up: interfaces and registries inside one codebase. The composition root (main, service providers) is the only place that changes when a variant is added.

Example (simple): a pricing engine with Discount implementations; adding a promotion is one file and one line in the provider.

Example (complex): a Laravel shop with a PaymentManager whose gateways come from three internal teams and one vendor package; each registers with extend() in its own service provider and none edits the manager.

Modular monolith and multiple databases ​

How it shows up: modules expose extension points to each other: events (OrderPlaced), contracts (ShippingRateProvider), tagged services. A module is closed against the modules that extend it.

Example: the Checkout module publishes OrderPlaced in-process; Loyalty, Invoicing and Analytics modules subscribe. Checkout's tables and code are never edited when a module is added. Each module keeps its own tables, so an extension never needs a schema change in the core module.

Microservices: plugins become services ​

What survives: the publisher stays closed through events on a broker, and the API stays closed through additive versioning. What breaks: synchronous fan-out. If checkout calls loyalty, invoicing and fraud over HTTP, every new downstream is an edit and a redeploy of checkout.

text
     Option A: orchestrated calls (not closed)       Option B: events (closed)
1    checkout -> POST /loyalty                       checkout: INSERT order + outbox(OrderPlaced); COMMIT
2    checkout -> POST /invoices                      relay publishes OrderPlaced to the topic
3    checkout -> POST /fraud  (new: edit checkout)   fraud-svc subscribes (new: no checkout change)

Webhooks are the same idea at the edge: a payment provider does not edit its code when you register a new endpoint. See Transactional Outbox and Event-Driven Architecture.

Distributed data: replicas, caches and schemas ​

Where OCP lives: in contracts that many parties read. A schema read by replicas, CDC pipelines and analytics is closed for modification: additive migrations only, expand/contract for the rest. A cache key format shared by services is a contract too: add a version prefix (v2:order:42) instead of changing the meaning of order:42. Event schemas in a registry with backward compatibility checks enforce OCP mechanically (Message Design & Schema Evolution).

Scaling path: 1×, 10×, 100× ​

ScaleExtension mechanismOCP practice
1× (one team)Interfaces, a switch until the third variantRule of three; no speculative hooks
10× (several teams, one deployable)Registries, Manager::extend, in-process eventsTeams add variants in their own modules and providers
100× (many services)Broker topics, webhooks, versioned APIs, schema registryPublishers closed against consumers; contracts only grow

Lab: refactoring kata ​

You turn a notification switch into a registry and measure what a new channel costs before and after.

Starting code.

go
// Package before is the OCP kata's starting point: every new channel is an
// edit to Send, to the Channel constants, and to the config validation.
package before

import (
	"context"
	"errors"
	"fmt"
)

type Channel string

const (
	Email Channel = "email"
	SMS   Channel = "sms"
)

type Message struct {
	To, Body string
}

var ErrUnknownChannel = errors.New("unknown channel")

func Validate(c Channel) error {
	switch c {
	case Email, SMS:
		return nil
	}
	return ErrUnknownChannel
}

func Send(ctx context.Context, c Channel, m Message) error {
	if err := ctx.Err(); err != nil {
		return err
	}
	switch c {
	case Email:
		fmt.Printf("SMTP to %s: %s\n", m.To, m.Body)
		return nil
	case SMS:
		fmt.Printf("SMS gateway to %s: %s\n", m.To, m.Body)
		return nil
	default:
		return fmt.Errorf("send via %q: %w", c, ErrUnknownChannel)
	}
}

Step 1: count the edit sites for "add push notifications". Expected: 3 edit sites in one file (a new Channel constant, a case in Validate, a case in Send), and the email and SMS paths must be retested because their function was edited.

Step 2: find the point of variation. Only "how a message is delivered on channel X" varies. Validation is a consequence (does a driver exist?), not a separate variation.

Step 3: introduce the abstraction and the registry. Compare with the reference: notify owns Driver, Register, Drivers and Send; email and sms register in init(); app is the composition root.

Step 4: add push. Create ocp/registry/push/push.go with a driver and func init() { notify.Register("push", driver{}) }, then add _ "academy/solid/ocp/registry/push" to app/main_wiring.go.

Step 5: measure.

bash
cd docs/snippets/solid/go
go vet ./ocp/...                                   # clean
git diff --stat -- ocp/registry/notify             # expected: no output (0 lines changed in the core)
go list -f '{{join .Imports " "}}' ./ocp/registry/notify
# context fmt sort sync    (the core imports no driver)
MetricBefore (switch)After (registry)
Edit sites in existing code to add a channel3 (constant, Validate, Send)1 (one blank import in the composition root)
Lines changed in the core5 (1 constant, 1 edited case list, 3 new lines in Send)0
Existing channels to retest2 (same function edited)0 (their packages unchanged)
Files touched1 edited1 new + 1 import line
Core imports of concrete driversn/a (inline)0
Who can add a channelOwner of notifyAny package

Step 6: the opposite axis. Now add a new operation: "every channel must support Preview(m) string". Expected: you must edit Driver and every driver (email, sms, push): the registry is closed against new channels, not against new operations. That is the Expression Problem.

Step 7 (Laravel, optional). In After.php, register a zarinpal driver with extend() from a new service provider. Expected: PaymentManager and PaymentService unchanged; git diff shows only the new provider and the new gateway class.

Common misconceptions ​

BeliefReality
OCP means never editing existing codeBugs and unexpected axes require edits; closure is strategic
Every class needs an interfaceOne implementation and no second actor = speculative generality
OCP needs inheritanceInterfaces, functions, registries, events and data tables all work
Go embedding lets you override the inner typeThe inner type's method set is not altered; you only add or wrap
Feature flags are OCPThey are temporary modifications; use them to pick a binding, then delete
Events make the system fully decoupledThe event schema becomes the closed contract
A good design is open in every directionThe Expression Problem: types or operations, pick the cheap axis
Adding fields to an API is always compatibleOnly optional additions; required or renamed fields break clients
switch statements violate OCPA switch over a closed, stable set is fine (and can be faster)
Plugins need dynamic loadingOCP is about source dependencies; compiled-in drivers qualify

Cheat sheet ​

TopicRemember
Definition (1996)Open for extension, closed for modification
Definition (2014)Extend behaviour without modifying the system
MechanismA module depends on a fixed abstraction; variants are new implementations
WhereAt the point of variation, sized to it
Strategic closureClose against likely changes only
WhenRule of three, or the moment another team adds variants
GoSmall interfaces, function types, embedding, generics, Register + init()
LaravelContracts, container (bind, tag, #[BindWhen]), Manager::extend, events
PluginsCore never imports plugins; plugins import the core
FlagsTemporary; flip a binding, not scattered ifs
APIs and schemasAdditive changes only; version to break
Protected VariationsLarman's name for the same principle
Expression ProblemInterfaces open new types; switches open new operations

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What did Meyer mean by "closed", and how did Martin's 1996 column change the mechanism? Good to know ​

Answer

Answer: Closed meant available for use by other modules (compiled, published, baselined). Meyer extended closed modules by inheritance; Martin's mechanism is depending on a fixed abstraction and adding new derivatives. See Where it comes from.

2 — Why can no program be 100% closed, and what do you do about it? Important ​

Answer

Answer: There is always some change against which a module is not closed. Closure must be strategic: choose the likely kinds of change and close against those. See Strategic closure.

3 — Where should the interface go in a payment service that will gain gateways? Must-know ​

Answer

Answer: At the point of variation: "charge this order through gateway X", one small PaymentGateway contract, not around the whole service. See Point of variation.

4 — How does database/sql stay closed against new databases? Must-know ​

Answer

Answer: Drivers implement database/sql/driver interfaces and call sql.Register in init(); main blank-imports them; the core never imports a driver. See Registry.

5 — Name three Laravel extension points documented in Laravel 13. Good to know ​

Answer

Answer: Cache::extend, Storage::extend, Auth::extend / Auth::provider; also container tag()/giveTagged() and #[BindWhen]. See Manager::extend.

6 — Is a feature flag an OCP extension point? Important ​

Answer

Answer: No: it is a temporary modification. Used well, it selects which implementation is bound at one toggle point and is deleted after rollout. See Feature flags vs OCP.

7 — You have one PdfRendererInterface with one implementation and no tests using a double. What smell is this and what do you do? Important ​

Answer

Answer: Speculative generality; inline the interface until a real second variant (or a test need) appears. See Speculative generality.

8 — Your interface-based design makes new shapes cheap. Why is adding Perimeter() expensive? Important ​

Answer

Answer: The Expression Problem: per-type classes are open to new cases but closed to new operations; every implementation must change. See Expression Problem.

9 — Which API changes are extensions and which are modifications? Must-know ​

Answer

Answer: Adding optional fields, endpoints or event types is extension; making fields required, renaming or retyping is modification and needs a new version. See OCP in APIs.

10 — How does Larman relate OCP, Protected Variations and information hiding? Good to know ​

Answer

Answer: He argues OCP and PV are two expressions of the same principle and that both are what Parnas meant by information hiding: identify points of predicted variation and create a stable interface around them. See Protected Variations.

Glossary ​

TermMeaning
Open–Closed Principle (OCP)Modules open for extension, closed for modification
Open (Meyer)Available for extension: new fields, new functions
Closed (Meyer)Available for use by other modules: stable, published
Point of variationThe smallest place where variants differ
Strategic closureChoosing which kinds of change a module is closed against
Plugin architectureCore owns an interface and registry; plugins depend on the core
Composition rootThe one place that names concrete implementations (main, service providers)
RegistryA map from names to implementations filled at start-up (sql.Register)
init() registrationGo pattern: a driver package registers itself when imported
Blank importimport _ "pkg": import for side effects (registration) only
EmbeddingGo struct composition; promotes inner methods without altering them
Generics (type parameters)Go 1.18+ functions and types parameterised by type
Contract (Laravel)An interface for a framework service (Illuminate\Contracts\...)
Service containerLaravel's dependency resolver: bind, singleton, tag, contextual binding
Service providerLaravel's bootstrapping class; where bindings and extend() calls go
Manager::extendLaravel API to register a custom driver creator by name
Tagged bindingsContainer tag() + giveTagged(): inject all implementations of a role
PSR-11PHP-FIG container interface with get and has
Feature flag (toggle)Runtime switch between code paths; release, experiment, ops or permissioning
Inversion of DecisionHodgson: make the toggle decision in one place and inject the result
Event-driven extensionPublisher announces facts; new consumers subscribe without editing it
Speculative generalityCode smell: hooks and abstractions nobody uses yet
Rule of threeRefactor to an abstraction on the third occurrence
Backward compatibilityNew versions accept old clients; only additive changes
Expand/contractSchema change in additive steps, removal later
Protected Variations (PV)GRASP: stable interface around predicted variation (Larman)
GRASPLarman's General Responsibility Assignment Software Patterns
Expression ProblemAdding both new cases and new operations without editing or losing type safety
Replace Conditional with PolymorphismRefactoring from a type-code switch to an interface
Data-driven closureVariants as rows or config entries, not code

References ​

Built by Morteza Negahi