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 for | Go to |
|---|---|
| The principle in a few tables | Everything in one minute |
| Why it exists, the trade-off, the analogy | Why OCP exists |
| Meyer 1988, Martin 1996 and 2014, Larman 2001, Wadler 1998 | Where it comes from |
| Open/closed, point of variation, strategic closure, plugins, flags, events, APIs, Protected Variations, Expression Problem | The concepts, one by one |
| Go, Laravel, Spring, .NET, TypeScript, Python mechanisms | Per-language and per-framework view |
Registries, init(), Manager, container tags, dispatch tables | Mechanics |
| Before/after code | Go, Laravel |
Growing switch, payment gateways, new storage driver, new event consumer | Solving the classic problems |
| When to abstract (rule of three) | Choosing |
| Plugins, events and versioned APIs across services | In architecture |
| A kata with before/after numbers | Lab: refactoring kata |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The ideas.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Open for extension | You can add new behaviour | A new discount type | Every feature edits old code |
| Closed for modification | Working code is not edited for that change | FinalPriceCents untouched | Retest of everything already working |
| Point of variation | The exact place where variants differ | "how a discount is computed" | Abstractions in the wrong place |
| Strategic closure | Choose which changes to be closed against | Close against new gateways, not new currencies | Abstract-everything bloat |
| Plugin architecture | Core knows an interface; plugins register | database/sql drivers | Core imports every vendor |
| Protected Variations | Stable interface around a predicted change | Larman's name for OCP | Change at one point ripples out |
| Speculative generality | Extension points nobody uses | PaymentStrategyFactoryInterface with one implementation | Cost with no benefit |
| Expression Problem | Adding cases vs adding operations | New shape vs new Perimeter() | Each design is closed on one axis only |
The mechanisms.
| Mechanism | Go | Laravel | Closed part | Open part |
|---|---|---|---|---|
| Interface + new type | type Discount interface{...} | interface PaymentGateway | The caller | The implementations |
| Registry | sql.Register, image.RegisterFormat | Cache::extend, Storage::extend, Auth::extend | The core package / manager | The drivers |
| Container | (manual wiring in main) | bind, tag + giveTagged, #[Bind], #[BindWhen] | The consumer class | The bound implementation |
| Events | Channels, callbacks | Events + listeners | The publisher | The subscribers |
| Composition | Struct embedding, middleware func(http.Handler) http.Handler | Middleware, decorators | The wrapped type | The wrapper |
| Generics | func Validate[T any](v T, rules ...Rule[T]) | (PHP has no generics; PHPStan templates) | The algorithm | The element types and rules |
| Data / table | Map of handlers | Config arrays, database rows | The engine | The rows |
Three things to do.
| Situation | Do this |
|---|---|
A switch on a type code grows every sprint | Replace it with an interface at that point, one type per case |
| Another team or package must add variants | Give them a registry (Register/extend) so they never edit your code |
| You think you might need variants one day | Write 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 switch | One more level of indirection to follow |
| Every new variant edits the same function | New variant = new file; old code untouched |
| All variants retested on each change | Only the new variant needs new tests |
| One team owns all variants | Other 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 variants | Right 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
- "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.
- "Put an interface on everything, just in case." That is speculative generality. Abstractions have a cost; wait for real variants.
- "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.
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.
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.
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 directlyFix (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.
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."
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.
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 creatorReal 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:
| Mechanism | What stays closed | What is open | Typical stdlib example |
|---|---|---|---|
| Implicit interface | The function taking the interface | Any type with the methods | io.Reader, http.Handler, sort.Interface |
| Function type | The caller | Any function of that signature | http.HandlerFunc, middleware |
| Embedding | The embedded type | The outer type's added/wrapped methods | bufio.ReadWriter embeds *Reader and *Writer |
| Generics | The algorithm | Element types (and rule types) | slices.SortFunc, maps.Keys |
Registry + init() | The core package | Registered drivers | sql.Register, image.RegisterFormat |
// 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().
// 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.
// 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 flag | OCP extension point | |
|---|---|---|
| Lifetime | Days to weeks (release toggles) | Years |
| Number of variants | Usually 2 (on/off) | Open-ended |
| Who adds variants | The same team | Other teams, packages, plugins |
| Cleanup | Must be deleted | Stays |
| Best combined | Flag 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.
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 generality | Example | Fix |
|---|---|---|
| Interface with one implementation and no test double | PdfRendererInterface → DomPdfRenderer only | Inline the interface |
| Factory that builds one thing | GatewayFactory::make('stripe') with no other branch | Call the constructor |
| Unused parameters "for later" | charge(Order $o, array $options = []) never used | Remove the parameter |
| Abstract base class with one child | AbstractExporter → CsvExporter | Collapse Hierarchy |
The full smell catalogue, with the moves that remove each smell, is the chapter Code Smells, Anti-Patterns & Refactoring.
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.
-- 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| Change | Compatible? | OCP reading |
|---|---|---|
| Add optional response field | Yes | Extension |
| Add new endpoint / event type | Yes | Extension |
| Add enum value consumers switch on | Risky | Consumers' switch is not closed |
| Make optional request field required | No | Modification |
| Rename or retype a field | No | Modification: 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.
| Design | New case (type) | New operation | Languages and tools |
|---|---|---|---|
| Interface / class per case | Cheap: new type | Expensive: edit every type | Go interfaces, PHP interfaces, Java/C# classes |
switch / pattern match over a closed set | Expensive: edit every switch | Cheap: new function | Go type switch, PHP match, TS discriminated unions with exhaustiveness checks |
| Visitor | Expensive | Cheap | GoF Visitor |
| Open dispatch | Cheap | Cheap (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 / framework | Primary extension point | Registry / discovery | Composition root | Note |
|---|---|---|---|---|
| Go | Small implicit interfaces, function types | Register + init() + blank import (database/sql, image) | main | Embedding extends without altering the inner type; generics since Go 1.18 |
| PHP / Laravel | Contracts (Illuminate\Contracts\*) | Managers' extend(), container tag(), event discovery | Service providers (bootstrap/providers.php) | PSR-11 ContainerInterface (get, has) standardises containers across frameworks |
| Java / Spring | Interfaces, abstract classes | Spring autowires "arrays and typed collections" of all candidate beans; JDK ServiceLoader | @Configuration classes | Inject List<DiscountRule> and a new @Component joins automatically |
| C# / .NET | Interfaces | Microsoft.Extensions.DependencyInjection; keyed services (GetKeyedServices) | Program.cs / IServiceCollection | Multiple registrations of one interface resolve as a sequence |
| TypeScript | Structural interfaces ("type compatibility in TypeScript is based on structural subtyping") | Plugin arrays in config (bundlers, linters) | App bootstrap | Discriminated unions are the "closed set" side of the Expression Problem |
| Python | Duck typing, typing.Protocol, ABCs | Package entry points via importlib.metadata.entry_points(); functools.singledispatch | Module that builds the app | Entry 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:
// 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)
}// 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"}) }// 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:
| Detail | Behaviour | Why |
|---|---|---|
| Duplicate name | panic (as sql.Register) | Two drivers claiming one name is a programming error; fail at start-up |
| Nil driver | panic | Same |
| Unknown name at use | Returned error (sql: unknown driver "x" (forgotten import?) in database/sql) | The usual cause is a missing blank import |
| Concurrency | Registry guarded by sync.RWMutex | init() order is per package; lookups may run concurrently |
| Discoverability | Drivers() returns sorted names | Debugging and health endpoints |
| Hidden dependency | Blank imports in main | Keep 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:
| Subsystem | Extension call | Where to register |
|---|---|---|
| Cache | Cache::extend('mongo', fn (Application $app) => Cache::repository(new MongoStore)) | In register() inside $this->app->booting(...), as the docs show |
| Filesystem | Storage::extend('dropbox', fn (Application $app, array $config) => new FilesystemAdapter(...)) | boot() |
| Auth guards | Auth::extend('jwt', fn (Application $app, string $name, array $config) => new JwtGuard(...)) | boot() |
| Auth user providers | Auth::provider('mongo', fn (Application $app, array $config) => new MongoUserProvider(...)) | boot() |
| Your own | PaymentManager 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.
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.
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.
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
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
// 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
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
Growing switch on a type code | Replace Conditional with Polymorphism | Interface at the point of variation, one type per case | New case = new file | Indirection; Expression Problem trade-off |
| Another team must add variants | Registry / Manager::extend | Register(name, impl) / extend('name', fn) | No edits to the core, no merge conflicts | Name collisions, hidden blank imports |
| Variants are values, not logic | Data-driven closure | Table or config rows | New variant without deploy | Not for new behaviour |
| New reactions to a business fact | Events | OrderPlaced + listeners / topic | Publisher closed | Event schema becomes the contract |
| Optional cross-cutting behaviour | Decorator / middleware / embedding | Wrap, do not edit | Composable | Order of wrappers matters |
| Temporary variation | Feature flag at one binding | #[BindWhen], Pennant | Safe rollout | Must be deleted |
New storage driver without touching the core
// 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 editedNew event consumer without touching the publisher
// 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
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| One variant, no roadmap for more | Direct code | None | Speculative generality costs now, pays never |
| Second variant arrives | Small switch or if | Name the axis in a comment | Rule of three: not enough evidence yet |
| Third variant, or a variant from another team | Interface at the point of variation | Registry / extend / tagged bindings | The axis is real |
| Variants differ only in numbers | Table or config | Admin UI over the table | Data-driven closure |
| Short-lived variation (A/B, rollout) | Feature flag | Flag selects a binding | Must be removed later |
| New reactions to a fact | Domain events | Queue listeners, outbox across services | Publisher closed against consumers |
| Public API / event schema | Additive changes only | Version for breaking changes | Clients cannot be edited |
| Hot loop over a closed set of types | switch | Benchmark | Dispatch cost; Expression Problem trade-off |
| Framework extension | Use the framework's hook | Cache::extend, sql.Register | Never 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.
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×
| Scale | Extension mechanism | OCP practice |
|---|---|---|
| 1× (one team) | Interfaces, a switch until the third variant | Rule of three; no speculative hooks |
| 10× (several teams, one deployable) | Registries, Manager::extend, in-process events | Teams add variants in their own modules and providers |
| 100× (many services) | Broker topics, webhooks, versioned APIs, schema registry | Publishers 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.
// 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.
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)| Metric | Before (switch) | After (registry) |
|---|---|---|
| Edit sites in existing code to add a channel | 3 (constant, Validate, Send) | 1 (one blank import in the composition root) |
| Lines changed in the core | 5 (1 constant, 1 edited case list, 3 new lines in Send) | 0 |
| Existing channels to retest | 2 (same function edited) | 0 (their packages unchanged) |
| Files touched | 1 edited | 1 new + 1 import line |
| Core imports of concrete drivers | n/a (inline) | 0 |
| Who can add a channel | Owner of notify | Any 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
| Belief | Reality |
|---|---|
| OCP means never editing existing code | Bugs and unexpected axes require edits; closure is strategic |
| Every class needs an interface | One implementation and no second actor = speculative generality |
| OCP needs inheritance | Interfaces, functions, registries, events and data tables all work |
| Go embedding lets you override the inner type | The inner type's method set is not altered; you only add or wrap |
| Feature flags are OCP | They are temporary modifications; use them to pick a binding, then delete |
| Events make the system fully decoupled | The event schema becomes the closed contract |
| A good design is open in every direction | The Expression Problem: types or operations, pick the cheap axis |
| Adding fields to an API is always compatible | Only optional additions; required or renamed fields break clients |
switch statements violate OCP | A switch over a closed, stable set is fine (and can be faster) |
| Plugins need dynamic loading | OCP is about source dependencies; compiled-in drivers qualify |
Cheat sheet
| Topic | Remember |
|---|---|
| Definition (1996) | Open for extension, closed for modification |
| Definition (2014) | Extend behaviour without modifying the system |
| Mechanism | A module depends on a fixed abstraction; variants are new implementations |
| Where | At the point of variation, sized to it |
| Strategic closure | Close against likely changes only |
| When | Rule of three, or the moment another team adds variants |
| Go | Small interfaces, function types, embedding, generics, Register + init() |
| Laravel | Contracts, container (bind, tag, #[BindWhen]), Manager::extend, events |
| Plugins | Core never imports plugins; plugins import the core |
| Flags | Temporary; flip a binding, not scattered ifs |
| APIs and schemas | Additive changes only; version to break |
| Protected Variations | Larman's name for the same principle |
| Expression Problem | Interfaces open new types; switches open new operations |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| 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 variation | The smallest place where variants differ |
| Strategic closure | Choosing which kinds of change a module is closed against |
| Plugin architecture | Core owns an interface and registry; plugins depend on the core |
| Composition root | The one place that names concrete implementations (main, service providers) |
| Registry | A map from names to implementations filled at start-up (sql.Register) |
init() registration | Go pattern: a driver package registers itself when imported |
| Blank import | import _ "pkg": import for side effects (registration) only |
| Embedding | Go 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 container | Laravel's dependency resolver: bind, singleton, tag, contextual binding |
| Service provider | Laravel's bootstrapping class; where bindings and extend() calls go |
Manager::extend | Laravel API to register a custom driver creator by name |
| Tagged bindings | Container tag() + giveTagged(): inject all implementations of a role |
| PSR-11 | PHP-FIG container interface with get and has |
| Feature flag (toggle) | Runtime switch between code paths; release, experiment, ops or permissioning |
| Inversion of Decision | Hodgson: make the toggle decision in one place and inject the result |
| Event-driven extension | Publisher announces facts; new consumers subscribe without editing it |
| Speculative generality | Code smell: hooks and abstractions nobody uses yet |
| Rule of three | Refactor to an abstraction on the third occurrence |
| Backward compatibility | New versions accept old clients; only additive changes |
| Expand/contract | Schema change in additive steps, removal later |
| Protected Variations (PV) | GRASP: stable interface around predicted variation (Larman) |
| GRASP | Larman's General Responsibility Assignment Software Patterns |
| Expression Problem | Adding both new cases and new operations without editing or losing type safety |
| Replace Conditional with Polymorphism | Refactoring from a type-code switch to an interface |
| Data-driven closure | Variants as rows or config entries, not code |
References
- Bertrand Meyer, Object-Oriented Software Construction, Prentice Hall, 1988, quoted via Martin's 2014 post.
- Robert C. Martin, "The Open-Closed Principle", Engineering Notebook, The C++ Report, 1996. PDF
- Robert C. Martin, Design Principles and Design Patterns, 2000. PDF mirror
- Robert C. Martin, "The Open Closed Principle", The Clean Code Blog, 12 May 2014. blog.cleancoder.com
- Robert C. Martin, "The Clean Architecture", 13 August 2012. blog.cleancoder.com
- Craig Larman, "Protected Variation: The Importance of Being Closed", IEEE Software, May/June 2001. PDF
- Philip Wadler, "The Expression Problem", email, 12 November 1998. Text
- Pete Hodgson, "Feature Toggles (aka Feature Flags)". martinfowler.com
- Dan North, "CUPID: the back story", 2021. dannorth.net
- Casey Muratori, ""Clean" Code, Horrible Performance", 28 February 2023. computerenhance.com
- Dave Cheney, "SOLID Go Design", 2016. dave.cheney.net; Rob Pike, Go Proverbs
- Go:
database/sql,image(RegisterFormat), Generics tutorial - Laravel 13: Service Container, Contracts, Service Providers, Cache: custom drivers, Filesystem: custom filesystems, Authentication: custom guards, Events, Pennant; source: Manager.php
- PHP-FIG, PSR-11: Container interface
- Spring Framework, Autowiring Collaborators; Microsoft, .NET dependency injection; TypeScript, Type Compatibility; Python, importlib.metadata, functools.singledispatch