Object-Oriented Modeling: Abstraction, Encapsulation, Decomposition, Generalization, Polymorphism
"OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things." — Alan Kay, e-mail to Stefan Ram, 23 July 2003
Summary: Object-oriented modeling turns a problem into objects that keep their own state, protect their own rules and talk only through requests. Five ideas carry the whole method: abstraction, encapsulation, decomposition, generalization and polymorphism. Focus: Precise definitions and where each idea came from (Simula, Smalltalk, Kay, Parnas, Liskov), essential vs accidental detail, information hiding vs data hiding, whole-part relationships, inheritance vs interfaces vs composition, the three kinds of polymorphism, identity and value objects, Tell-Don't-Ask, traits and Go embedding, and how the model changes when it crosses a service boundary. Learning goal: Take a few domain sentences, produce a small object model whose invariants cannot be broken from outside, write it in Go and in PHP 8.4 with Laravel 13, and know which parts of it may and may not leave the process.
This page is the foundation the rest of the design section builds on. It covers the five modeling ideas completely, with their history, the vocabulary practitioners use, the mechanisms in Go and PHP, the classic modeling mistakes, and what an object model becomes in a modular monolith and in microservices. It does not re-teach its neighbours: how to find classes with CRC cards is on The Design Process, the notation is on UML in Practice, responsibilities and class relationships at code level are on Low-Level Design, coupling and cohesion are on Design Quality, the Law of Demeter is on Composing Objects, substitutability rules are on Liskov Substitution, small interfaces are on Interface Segregation, factories are on Creational Patterns, and the DDD versions of entities and value objects are on Entities & Value Objects and Anemic vs Rich Domain Models.
Page map
| If you are looking for | Go to |
|---|---|
| The five ideas and the vocabulary in a few tables | Everything in one minute |
| Why we model with objects at all, and what it costs | Why it exists |
| Simula, Smalltalk, Kay, Parnas, Liskov, Cardelli and Wegner, GoF | Where it comes from |
| Object, abstraction, encapsulation, decomposition, generalization, polymorphism | The concept catalogue |
| Fragile base class, objects vs data structures, value objects, Tell-Don't-Ask, traits, embedding, construction | The concept catalogue (later blocks) |
| How Go, PHP, Simula, Smalltalk, CLU and Python express the ideas | Per-language view |
| Dynamic dispatch, from sentences to classes, invariants | Mechanics |
| Before/after code | Go, Laravel |
| Anemic model, god object, deep hierarchies, inheritance for reuse | Solving the classic problems |
| Inheritance or interface or composition or generics | Choosing |
| Object model vs service contracts, DTOs at boundaries | In architecture |
| Run it yourself | Lab |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The five modeling ideas. Every row is unpacked in the concept catalogue.
| Idea | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Abstraction | Keep what matters for this problem, drop the rest | Order has lines and a total, not a warehouse shelf number | Models drown in detail and change for irrelevant reasons |
| Encapsulation | State changes only through the object's own operations | order.Place(pay) instead of order.Status = "placed" | Any caller can break the rules; invariants live everywhere |
| Decomposition | Split a whole into parts with clear ownership and lifetime | Order owns OrderLines; it only knows its Customer | God objects, or parts that outlive the thing they belong to |
| Generalization | Relate a type to a more general one it behaves like | Card and Wallet are both a PaymentMethod | Duplicated switches on type codes in every function |
| Polymorphism | One request, many implementations, chosen per object | pay.Charge(total) works for any payment method | Callers must know every concrete type |
Relationships between objects (UML names; the details are in Decomposition).
| Relationship | Reads as | Lifetime | Example | Go | PHP / Laravel |
|---|---|---|---|---|---|
| Dependency | "uses for a moment" | None | Order.Place takes a PaymentMethod argument | Parameter | Parameter, container injection |
| Association | "knows a" | Independent | Order knows its customer | Field holding an ID or pointer | belongsTo |
| Shared aggregation | "groups" | Parts may outlive the whole | Playlist groups Songs | Slice of IDs or pointers | belongsToMany |
| Composition (composite aggregation) | "is made of" | Parts die with the whole, one owner | Order is made of OrderLines | Unexported slice of values | hasMany + cascadeOnDelete |
| Generalization | "is a kind of" | n/a | PremiumCustomer is a Customer | Not available (no type hierarchy) | extends |
| Realization | "behaves like" | n/a | Card implements PaymentMethod | Implicit (method set) | implements |
Three kinds of polymorphism (Strachey, refined by Cardelli and Wegner, 1985).
| Kind | Family | In plain words | Go | PHP 8.4 |
|---|---|---|---|---|
| Subtype (inclusion) | Universal | One interface, many classes | Interfaces, satisfied structurally | Interfaces and extends, declared nominally |
| Parametric | Universal | One body of code, any type that fits | Generics since Go 1.18 (Max[T cmp.Ordered]) | Not in the language; docblock generics for static analysers only |
| Ad-hoc: overloading | Ad-hoc | Same name, different code per type | Not available | Not available in the classic sense: PHP "overloading" means __call/__get |
| Ad-hoc: coercion | Ad-hoc | Value converted to fit | Explicit conversions only | Type juggling in non-strict mode |
Objects that hold data.
| Kind | Equal when | Mutable? | Example | Go | PHP 8.4 |
|---|---|---|---|---|---|
| Value object | All attributes equal | No, replace it | Money{2250, "EUR"} | Struct with comparable fields, == | final readonly class, equals() |
| Entity (reference object) | Same identity | Yes, through methods | Order o-1 | Pointer + ID, SameAs() | Class with ID; Eloquent $a->is($b) |
| Data structure / DTO | n/a (no behaviour) | Usually not | OrderPlacedV1 | Exported fields + JSON tags | readonly class with public properties |
Why it exists
A program has to hold a model of something: orders, accounts, trains, documents. The question is where the rules of that something live. In a procedural design the data sits in records and the rules sit in procedures that anyone can call with any record. That works until the rules multiply and the same check is copied into ten procedures, one of which forgets it. Object-oriented modeling puts each rule next to the data it protects, behind a small set of operations, so the rule is written once and cannot be skipped.
| Data plus procedures | Objects |
|---|---|
| Data is visible to every procedure | Data is visible only to the object's own operations |
| A rule is checked wherever someone remembers to check it | A rule is checked in one method, every time |
| Adding a new operation is easy: write one function | Adding a new operation means touching every class |
Adding a new kind of thing means editing every switch | Adding a new kind means adding one class |
| Easy to serialise and send across a network | Hidden state must be mapped to a contract first |
| Risk: anemic data and scattered rules | Risk: deep hierarchies, god objects, over-abstraction |
The third and fourth rows are not a typo: Robert Martin's 2019 dialogue shows that the two styles are opposites, and each is easy where the other is hard (see Objects vs data structures). Object modeling is a choice, not a law.
The picture puts one object in the middle (state plus behaviour behind an interface) and the five ideas around it. Abstraction decides what the object is; encapsulation decides who may change it; decomposition splits it into parts; generalization relates it to more general types; polymorphism lets one message reach many implementations. Underneath all five is Kay's point: objects only talk by sending requests.
The analogy we reuse on this page: a car. The driver sees a steering wheel, pedals and a speedometer, not fuel injection timing: that is abstraction. The engine bay is closed and the only way to make the car faster is the accelerator: encapsulation. The car is made of an engine, four wheels and a body; the engine belongs to one car, while the road it drives on belongs to nobody: decomposition. A car, a van and a truck are all vehicles you can drive with the same licence: generalization. Pressing "accelerate" works in a petrol car, a diesel and an electric car, each doing something different under the bonnet: polymorphism.
Three common misunderstandings, up front
- "Object-oriented means inheritance." Kay deliberately left inheritance out of early Smalltalk ("I decided to leave out inheritance as a built-in feature until I understood it better"), and Go has no type hierarchy at all. The core ideas are messaging, hiding and late binding; inheritance is one optional tool for generalization.
- "Encapsulation means private fields with getters and setters." A class whose every field has a public setter hides nothing: any caller can still put it into any state. Encapsulation means the object decides which state changes are allowed.
- "A good model mirrors the real world." The Gang of Four warn that "Strict modeling of the real world leads to a system that reflects today's realities but not necessarily tomorrow's." A model is shaped by the questions the software must answer and by what will change, not by what exists physically.
Where it comes from
Simula, 1960s. Ole-Johan Dahl and Kristen Nygaard's Simula I and Simula 67 introduced classes, instances and subclasses for simulation programs. Cardelli and Wegner's 1985 survey states it plainly: "Simula is the first object-oriented language." They also note what Simula lacked: its class instances "lack the information-hiding mechanism of data abstractions", which later languages such as Smalltalk added.
Kay and Smalltalk, 1967 to the 1970s. Alan Kay says he coined the term at Utah "sometime after Nov 66", influenced by Sketchpad, Simula, the ARPAnet design and biology, and that "The original Smalltalk at Xerox PARC came out of the above." His 2003 e-mail describes objects as "like biological cells and/or individual computers on a network, only able to communicate with messages", and gives the definition in the title quote. His Early History of Smalltalk adds the image that still explains the idea best:
"In computer terms, Smalltalk is a recursion on the notion of computer itself." — Alan Kay, The Early History of Smalltalk, 1993
Parnas, 1972. David Parnas's On the Criteria To Be Used in Decomposing Systems into Modules gave modular design its central rule, which is the origin of encapsulation as a design (not language) idea:
"We propose instead that one begins with a list of difficult design decisions or design decisions which are likely to change. Each module is then designed to hide such a decision from the others." — D. L. Parnas, On the Criteria To Be Used in Decomposing Systems into Modules, CACM 15(12), 1972
Liskov, Zilles and Guttag, 1974 onwards. Barbara Liskov and Stephen Zilles's Programming with abstract data types (SIGPLAN, 1974) and the CLU language made the abstract data type a programming construct; Liskov and John Guttag's Abstraction and Specification in Program Development (MIT Press, 1986) is the textbook of the method. We read neither directly; both are cited from Liskov's 1987 keynote, which we did read. That keynote defines the goal of abstraction in one sentence:
"The purpose of abstraction in programming is to separate behavior from implementation." — Barbara Liskov, Data Abstraction and Hierarchy, OOPSLA '87 keynote
and the data abstraction itself: "a data abstraction is a set of objects that can be manipulated directly only by a set of operations." The same paper is the first statement of the substitution property behind Liskov Substitution, and an early warning about inheritance: subclasses "are typically permitted to violate encapsulation" (crediting Alan Snyder's OOPSLA '86 paper, which we did not read).
Cardelli and Wegner, 1985. On Understanding Types, Data Abstraction, and Polymorphism gave the definition most textbooks still repeat, "object-oriented = data abstractions + object types + type inheritance", and the classification of polymorphism used on this page.
Brooks, 1986. No Silver Bullet split software difficulty into essence and accident, and counted object-oriented programming as two separate advances, abstract data types and hierarchical types, noting "there may be hierarchies without hiding and hiding without hierarchies." It also predicted that neither would give an order-of-magnitude gain, because they remove accidental, not essential, complexity.
Gang of Four, 1994. Design Patterns (Gamma, Helm, Johnson, Vlissides) chapter 1 gave the two principles every modern design discussion quotes, "Program to an interface, not an implementation." and "Favor object composition over class inheritance.", and the white-box vs black-box reuse vocabulary.
Fowler and Evans, 2003. Martin Fowler's AnemicDomainModel named the anti-pattern of objects without behaviour; Eric Evans's Domain-Driven Design (summarised in the free DDD Reference, 2015) made the entity vs value object distinction standard vocabulary.
Go, 2009, and PHP 8.x. Go (the FAQ: "Go became a public open source project on November 10, 2009.") chose "no type hierarchy" and implicit interfaces from the start, and added parametric polymorphism with generics in Go 1.18 (the Go blog, March 2022). PHP added enums and readonly properties in 8.1, readonly classes in 8.2, and property hooks and asymmetric visibility in 8.4.
What about "the four pillars"? The list "abstraction, encapsulation, inheritance, polymorphism" is textbook and interview folklore; we found no primary source that defines it. Kay himself, asked whether OOP means "inheritance, polymorphism and encapsulation", answered with messaging, hiding and late binding instead. This page uses generalization (the design idea) rather than inheritance (one mechanism for it), and adds decomposition, because deciding what is a part of what is half of modeling.
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a sequence, real scenarios, how languages provide it, and the fix in Go and Laravel. The running example is a small shop: customers place orders of lines, pay by card or wallet, and can cancel a placed order.
Object, class and message Must-know
In plain words: an object is a thing in the program that remembers something (its state) and knows how to do something with it (its behaviour). You do not touch its memory; you ask it to do things. A class is the recipe for a family of similar objects.
Common misunderstanding: "An object is a struct with functions attached." That describes the implementation in C++ or Go, not the idea. The defining property is that the only way in is a request: GoF chapter 1 says "Requests are the only way to get an object to execute an operation. Operations are the only way to change an object's internal data."
Definition: an object packages state and the operations on that state; its interface is the set of requests it accepts (GoF: "The set of all signatures defined by an object's operations is called the interface to the object"); a class specifies the implementation shared by a set of objects; a message (request, method call) names an operation, and the receiving object chooses the method that runs. Kay's three properties are the test: messaging, protected local state, late binding.
Caller (checkout) Order o-1 (object) PaymentMethod (object)
1 o.Place(card) -> is status draft? has lines?
2 total := sum of lines
3 card.Charge(total) -> charge, return receipt
4 status = placed <- "card *4242 charged 22.50 EUR"
5 <- nil (or an error) caller never touched status, lines or totalReal scenario: an Order that refuses lines after it is placed; a Wallet that refuses a charge above its balance; a Session object in a web framework that renews itself when asked, without the controller knowing the storage.
How languages provide it: Smalltalk sends real messages to any object; PHP and Go call methods on a receiver, statically checked in Go; in all three the receiver decides the implementation (see dynamic dispatch).
Fix: if callers assign fields on your type, add an operation named after the business action (Place, Cancel, AddLine) and make the fields private.
Abstraction Must-know
In plain words: abstraction is deciding what to leave out. An order in a shop needs lines, a total and a status; it does not need the colour of the box it ships in.
Common misunderstanding: "Abstraction means an abstract class or an interface." Those are mechanisms that let you write an abstraction down. The abstraction is the decision about what the caller needs to know, and you make it whether or not your language has the keyword.
Definition: Liskov: "The purpose of abstraction in programming is to separate behavior from implementation." A specification says what the abstraction does; any implementation that meets it is acceptable. Abstraction comes in kinds and in levels:
| Kind | What is hidden | Example |
|---|---|---|
| Procedural abstraction | How a task is done | Total() hides the summing loop |
| Data abstraction (abstract data type) | How data is represented | Money hides whether it stores cents or a decimal string |
| Control abstraction | How iteration or sequencing happens | Go range, PHP foreach over an IteratorAggregate |
| Abstraction level (layer) | Everything below the current level | Checkout talks about "place order", not "UPDATE orders SET" |
Essential vs accidental. Brooks borrowed the distinction from Aristotle: "The essence of a software entity is a construct of interlocking concepts: data sets, relationships among data items, algorithms, and invocations of functions." The essential part of Order is the rule "lines can only be added to a draft"; storing it in PostgreSQL, serialising it as JSON or mapping it with Eloquent is accidental. A good abstraction keeps the essential and pushes the accidental behind other abstractions.
Level Talks about Must not mention
1 Use case "place order o-1 with card *4242" SQL, HTTP status codes
2 Domain Order, OrderLine, Money, Status table names, JSON
3 Persistence rows, columns, transactions HTTP, UI
4 Transport requests, headers, status codes business rules
-- each level uses the one below through an interface, never by reaching past it --Real scenario: a payment abstraction that hid "card" so well that adding a wallet was one class; a Money type that let a team switch from float to integer cents in one file; a report service whose abstraction leaked SQL into the controller, so a column rename broke the API.
Fix: write the abstraction as the smallest interface the caller needs (Charge(amount Money) (string, error)), in the caller's words, and keep every accidental detail out of it.
Encapsulation and information hiding Must-know
In plain words: encapsulation is the fence around an object's state: only its own methods may change it. Information hiding is the reason for the fence: the decision behind it is likely to change, so nobody outside should depend on it.
Common misunderstanding: "Private fields are encapsulation." Private fields are data hiding, a language feature. If the same class has setStatus(string), the data is hidden but the information is not: every caller still depends on the status values and on the rule of when they may change. Conversely, Parnas's modules hide decisions, which can be an algorithm, a file format or the order of steps, not only fields.
Definition: three terms that are often blurred:
| Term | Level | What it means | Source |
|---|---|---|---|
| Information hiding | Design | Each module hides a design decision likely to change | Parnas 1972 |
| Encapsulation | Design + language | The representation can be manipulated only through the abstraction's operations | Liskov 1987: "For abstraction to work, implementations must be encapsulated." |
| Data hiding (access control) | Language | Compiler or runtime blocks access to members | Go lowercase identifiers; PHP private, protected, private(set) |
An invariant is a condition that is true for every object of the class whenever no method is running: "a placed order has at least one line", "money is never negative", "all lines share one currency". Encapsulation is what makes an invariant enforceable: if only the methods change state, only the methods need to check it.
Without encapsulation (before/main.go) With encapsulation (after/ordering/order.go)
1 o.Lines = append(o.Lines, Line{Qty: -3}) o.AddLine("mug", -3, eur(500))
2 -- accepted, total now wrong -- -- ErrBadQuantity, order unchanged --
3 o.Status = "shiped" o.status is unexported; no setter exists
4 -- typo compiles and is saved -- -- only Place and Cancel change status --Real scenario: a Subscription whose ends_at was written by six controllers and three jobs, each with its own idea of a grace period; an inventory count decremented by two code paths, one of which skipped the "not below zero" check; a Go struct with exported fields that a JSON decoder filled with an impossible state.
How languages provide it:
| Mechanism | Go | PHP 8.4 |
|---|---|---|
| Hide a member | Lowercase name: invisible outside the package | private (class), protected (class + subclasses) |
| Read-only from outside | Unexported field + exported getter method | public private(set) or public protected(set) (asymmetric visibility) |
| Write once | No keyword; set only in the constructor function | readonly property, readonly class (all properties) |
| Hide a whole type | Unexported type name (line) | No private classes; @internal docblock + architecture tests |
| Hide a whole package | internal/ directory | Namespaces only; Composer cannot hide classes |
| Derived value | Method (Total()) | Virtual property with a get hook (public Money $total { get => ... }) |
Fix: Go: unexported fields, a constructor function, methods named after business actions. PHP 8.4: private(set) for state that outsiders may read, readonly for values, methods for transitions. Note the PHP rules we verified on php.net: "Property hooks are incompatible with readonly properties", and "A property with private(set) visibility is automatically final".
Decomposition: whole and part Must-know
In plain words: decomposition is splitting one big thing into smaller things and deciding, for each pair, how tightly they belong together. Some parts cannot exist without the whole (an order line without its order); some things are merely known (the customer of an order).
Common misunderstanding: "Aggregation and composition are the same thing; both mean 'has a'." They differ in lifetime and sharing, and worse, the words mean different things in different books (see the warning below).
Definition: the questions that classify a whole-part relationship:
| Question | Answer A | Answer B |
|---|---|---|
| Fixed or dynamic? | Fixed: the number of parts is set by the type (a car has 4 wheels, an Address has 3 fields) | Dynamic: parts come and go at run time (an order's lines) |
| Lifetime | Part dies with the whole | Part lives on independently |
| Sharing | Part belongs to exactly one whole at a time | Part can belong to several wholes |
| Who creates the part? | The whole (through its methods) | Someone else, then linked |
| Who may change the part? | Only the whole | Anyone with a reference |
UML 2.5.1 (section 9.5.3) defines the relationship kinds formally. AggregationKind has three values, none, shared and composite:
"Composite aggregation is a strong form of aggregation that requires a part object be included in at most one composite object at a time. If a composite object is deleted, all of its part instances that are objects are deleted with it." — OMG, Unified Modeling Language 2.5.1, section 9.5.3
For shared aggregation the spec says only "Precise semantics of shared aggregation varies by application area and modeler." Fowler's summary, quoting Jim Rumbaugh, is that the white diamond is "a modeling placebo".
Three meanings of "aggregation"
In UML, aggregation (white diamond, shared) has no fixed meaning and composition (black diamond, composite) means one owner and shared lifetime. In the GoF book, "Aggregation implies that an aggregate object and its owner have identical lifetimes", which is UML's composition, and their "acquaintance" is UML's association. In DDD, an Aggregate is a consistency boundary of entities and value objects with one root (see Aggregates & Factories). This page uses the UML words.
The picture shows the three columns side by side. On the left an Order knows its Customer (association): both live independently and many orders point to one customer, mapped as a foreign key that refuses to delete a customer who still has orders. In the middle a Playlist groups Songs (shared aggregation): a song is in many playlists and survives their deletion, mapped as a join table. On the right an Order is made of OrderLines (composition): each line has one owner and is deleted with it, mapped as a non-null foreign key with cascade.
Event Association (Customer) Shared aggr. (Song) Composition (OrderLine)
1 whole created customer already exists songs already exist no lines yet
2 part added link by customer_id insert playlist_song order.AddLine(...) creates it
3 part shared with another whole yes, many orders yes, many playlists never
4 whole deleted customer stays songs stay lines deleted with the orderReal scenario: invoice lines that survived their invoice and showed up in tax totals (composition modelled as association); tags deleted when one article was deleted (association modelled as composition); a Team object that held full User objects and saved them, so editing a team overwrote user profiles (a shared part treated as owned).
How it maps to storage (PostgreSQL; the same shape works in MySQL InnoDB):
-- Association: an order knows its customer; the customer outlives it.
CREATE TABLE orders (
id text PRIMARY KEY,
customer_id text NOT NULL REFERENCES customers(id) ON DELETE RESTRICT,
status text NOT NULL CHECK (status IN ('draft','placed','cancelled')),
-- Value object embedded as columns: no identity, no table of its own.
ship_street text NOT NULL, ship_city text NOT NULL, ship_country char(2) NOT NULL,
currency char(3) NOT NULL
);
-- Composition: one owner, deleted with it, never shared.
CREATE TABLE order_lines (
order_id text NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
line_no int NOT NULL,
sku text NOT NULL,
quantity int NOT NULL CHECK (quantity > 0),
unit_price_cents bigint NOT NULL CHECK (unit_price_cents >= 0),
currency char(3) NOT NULL, -- Money = (unit_price_cents, currency); equals orders.currency
PRIMARY KEY (order_id, line_no) -- the part's identity is local to its whole
);
-- Shared aggregation: parts live on their own; only the link rows belong to the whole.
CREATE TABLE playlist_song (
playlist_id bigint NOT NULL REFERENCES playlists(id) ON DELETE CASCADE,
song_id bigint NOT NULL REFERENCES songs(id) ON DELETE RESTRICT,
PRIMARY KEY (playlist_id, song_id)
);Fix: Go: make the part type unexported (line) and create it only inside the whole's methods; hold associations by ID, not by pointer, when the other object has its own lifecycle. Laravel: hasMany plus cascadeOnDelete() in the migration for composition, belongsTo for association, belongsToMany for shared aggregation, and create parts through the whole ($order->addLine(...)).
Generalization: inheritance, interfaces and composition Must-know
In plain words: generalization says "this thing is a kind of that thing" or "this thing can be used wherever that thing is expected". It is what lets checkout accept "any payment method".
Common misunderstanding: "Generalization means extends." Class inheritance is one way to write it, and the riskiest. Interfaces, Go's implicit interfaces and composition with delegation express the same design idea with less coupling.
Definition: GoF separate two things languages often merge: "Class inheritance defines an object's implementation in terms of another object's implementation. In short, it's a mechanism for code and representation sharing. In contrast, interface inheritance (or subtyping) describes when an object can be used in place of another." Liskov makes the same split: "subclass" is a language mechanism, "subtype" is a semantic promise.
| Relationship | Question to ask | Mechanism | Coupling |
|---|---|---|---|
| is-a (subtype) | Can it be used everywhere the general type is, with no surprises? | Interface; extends only if the LSP contract holds | Low with interfaces |
| behaves-like | Does it answer the same requests? | Interface (PHP nominal, Go structural) | Low |
| is-implemented-in-terms-of | Do I just want its code? | Composition + delegation, never extends | Low |
| has-a | Does it own or know the other? | Field (composition or association) | Depends on lifetime |
White-box vs black-box reuse. GoF: "Reuse by subclassing is often referred to as white-box reuse", because "the internals of parent classes are often visible to subclasses"; composition "is called black-box reuse, because no internal details of objects are visible." Their conclusion, after listing advantages on both sides, is the principle "Favor object composition over class inheritance." It is a preference, not a ban: "Inheritance and object composition thus work together."
On the left, SMSNotifier inherits from Notifier and quietly depends on the fact that Send calls Channel() on itself; the relationship is fixed when the code is compiled, and a change to the base class reaches every subclass. On the right, Sender holds a Channel interface; SMS and Email implement it, only the interface is visible, and the part can be swapped at run time. The left side shows class inheritance as PHP implements it, where the subclass's Channel() wins inside Send; the Go program in embedding uses the same names and prints [email] instead, because Go embedding has no override through self-calls.
Year Change Inheritance tree Composition
1 Y1 Notifier with Email; SMSNotifier extends it 2 classes Sender + Email + SMS
2 Y2 add Push PushNotifier extends Notifier + Push (Channel)
3 Y2 add "retry 3 times" to all channels edit base: all subclasses RetryingChannel wraps any Channel
4 Y3 add "SMS with retry but no logging" new subclass of a subclass compose SMS in RetryingChannel
5 Y3 base Notifier.Send refactored 2 subclasses break (fragile) nothing to re-test outside SenderReal scenario: a BaseController with 40 helpers that every controller inherits; an AbstractRepository whose save() changed and broke three repositories; Laravel's own Model base class, which is a deliberate framework choice: you extend it, and you read the upgrade guide on every major version because its behaviour reaches your subclass.
Fix: model "behaves-like" with an interface (PaymentMethod), share code by composition (RetryingChannel{inner Channel}), and keep extends for real subtypes or for framework base classes you are required to extend. In Go the decision is made for you: there is no class inheritance.
The fragile base class problem Important
In plain words: a change that looks safe inside a base class breaks a subclass somebody else wrote, because the subclass depended on how the base class calls itself.
Common misunderstanding: "If the base class's public methods keep their signatures, subclasses are safe." Signatures are not the contract a subclass depends on. Which method calls which (self-calls) is also part of it, and it is invisible.
Definition: Mikhajlov and Sekerinski's A Study of the Fragile Base Class Problem describes it in systems that use "code inheritance as an implementation reuse mechanism along with self-recursion": developers unaware of extensions "may produce a seemingly acceptable revision of a base class which may damage its extensions." Their one-line summary: "Classes in the foundation of an object-oriented system can be fragile." GoF give the cause: "inheritance breaks encapsulation" (they cite Snyder 1986).
Step Base class TagSet (shared package) Subclass CountingTagSet (application)
1 v1 addMany() loops and calls add() overrides add() and addMany() to count attempts
2 addMany(['a','b']) attempts = 2 (addMany) + 2 (add via self-call) = 4 -- bug
3 team "fixes" it by removing its addMany override: attempts = 2, correct, but now depends on the self-call
4 v2 base optimises addMany() to write the array directly, no self-call
5 addMany(['a','b']) attempts = 0 -- broken again, nobody touched the subclassReal scenario: framework upgrades that change the order of hook methods in a base controller; a collection class whose addAll stopped calling add; ORM base models whose save() started firing an extra event.
Fix: composition with forwarding to an interface, so the wrapper depends only on the interface contract, not on the inner object's self-calls. The PHP version is in inheritance for code reuse. Go is immune by construction: an embedded type's methods always run with the inner receiver (see traits and embedding). When you must publish a base class, mark everything final except documented extension points, and document which methods call which.
Polymorphism: subtype, parametric and ad-hoc Must-know
In plain words: polymorphism means one piece of calling code works with many types. "Charge this amount" works for a card and a wallet; "find the maximum" works for ints and strings.
Common misunderstanding: "Polymorphism means overriding methods in subclasses." That is one kind (subtype polymorphism through inheritance). Generics are polymorphism too, and so is a function that behaves differently for an int and a string.
Definition: Strachey (1967), as quoted by Cardelli and Wegner: "Parametric polymorphism is obtained when a function works uniformly on a range of types: these types normally exhibit some common structure. Ad-hoc polymorphism is obtained when a function works, or appears to work, on several different types (which may not exhibit a common structure) and may behave in unrelated ways for each type." Cardelli and Wegner add inclusion (subtype) polymorphism "to model subtypes and inheritance":
| Kind | Same code for all types? | Checked | Go | PHP 8.4 |
|---|---|---|---|---|
| Subtype / inclusion | No: each type has its own method, chosen at run time | Go: compile time; PHP: run time (type declarations) | interface { Charge(Money) (string, error) } | interface PaymentMethod, extends |
| Parametric (generics) | Yes: one body | Compile time | func Max[T cmp.Ordered](xs ...T) T, Stack[T any] | None in the language; PHPStan/Psalm @template |
| Ad-hoc: overloading | No: one body per type | Compile time | Not supported | Not supported; the manual: "PHP's interpretation of overloading is different than most object-oriented languages" |
| Ad-hoc: coercion | Converted first | Either | Only explicit conversions | Type juggling unless declare(strict_types=1) |
| Ad-hoc by type switch | No: a switch on type | Run time | switch x := v.(type) | match (true) { $v instanceof ... } |
Nominal vs structural typing, and duck typing.
| Style | Rule | Example |
|---|---|---|
| Nominal | A type is a subtype only if it declares it (implements, extends) | PHP: final class CardPayment implements PaymentMethod |
| Structural | A type is a subtype if it has the methods | Go interfaces: the Go FAQ says "a type automatically satisfies any interface that specifies a subset of its methods" |
| Duck typing | No check at all until the call; if the method exists, it runs | Python's glossary: "A programming style which does not look at an object's type to determine if it has the right interface; instead, the method or attribute is simply called or used" |
GoF define the subtype kind in terms of late binding: dynamic binding "lets you substitute objects that have identical interfaces for each other at run-time. This substitutability is known as polymorphism, and it's a key concept in object-oriented systems."
Call Go resolves PHP resolves
1 pay.Charge(total) interface value (T=*Wallet, V=ptr) -> $payment is WalletPayment ->
2 method of *Wallet, at run time WalletPayment::charge, at run time
3 Max(3, 9, 4) T=int, checked at compile time n/a (no generics)
4 Describe(1.5) type switch -> default branch match(true) -> default armReal scenario: a notification service with one Notifier interface and channels added per country; a generic Cache[K comparable, V any] in Go that replaced five copy-pasted caches; a reporting function full of instanceof checks that broke every time a type was added (ad-hoc where subtype was wanted).
Fix: use subtype polymorphism when the set of types grows; use generics when the algorithm is the same for all types; use a type switch or match only when the set of types is closed and small (see objects vs data structures for why).
Objects vs data structures Important
In plain words: an object hides its data and shows behaviour; a data structure shows its data and has no behaviour. Both are useful; mixing them gives you the worst of each.
Common misunderstanding: "Everything in an OO program should be an object." Request payloads, messages on a queue, rows from a table and API responses are data structures, and treating them as objects (adding behaviour, hiding fields) fights the serialiser and the network.
Definition: Robert Martin's 2019 dialogue Classes vs. Data Structures: "An object is a set of functions that operate upon encapsulated data elements." and "A data structure is a cohesive set of data elements." His conclusions:
| Statement (Martin 2019) | Consequence |
|---|---|
| "Objects are the opposite of data structures." | Do not give a DTO behaviour, do not give an entity public fields |
| "DTOs are data structures." | Request/response/message types are plain data |
| "Databases contain data structures, not objects." | Tables are not your object model; ORMs move data between data structures |
| Adding a new type is easy with objects, hard with data structures | Polymorphism when types grow |
| Adding a new function is easy with data structures, hard with objects | Functions + switch when operations grow and types are closed |
This trade-off is often called the expression problem; we did not find it named in Martin's post, so treat the name as common usage. Martin's Clean Code (2008, chapter 6) argues the same point; we did not read the book and cite the blog post instead.
Change request Objects (Shape interface) Data structures (switch on kind)
1 add Triangle add one type, nothing else edits edit Area(), Perimeter(), Draw()
2 add Centroid() edit Rect, Circle, Triangle add one function
3 send shapes to another service map each object to a DTO first marshal as-isReal scenario: an Eloquent model returned straight from a controller, so a new column leaked to the public API; a Go domain struct with JSON tags whose field rename broke three consumers; a DTO with a save() method that made the transport layer depend on the database.
Fix: objects inside the domain, data structures at every edge: HTTP (Laravel Form Requests and API Resources, Go request/response structs), queues (event DTOs) and storage (rows). Map explicitly between them; see the boundary snippets.
Identity, equality and immutability: value objects and entities Must-know
In plain words: some objects are "the same" when their values match (two 10-euro notes are interchangeable); others are "the same" only if they are the same individual (two customers called Ana are not one person). The first kind should never change; the second kind changes through its life.
Common misunderstanding: "== tells me whether two objects are equal." It depends on the language and on the kind of object. PHP's == compares attributes of two instances of the same class, === compares identity; Go's == compares struct values field by field and pointers by address; neither knows that two Customer objects with different e-mails but the same ID are the same customer.
Definition:
| Concept | Meaning | Source |
|---|---|---|
| Identity | What makes an object this one across all changes | Evans: "When an object is distinguished by its identity, rather than its attributes, make this primary to its definition in the model." |
| Equality | A rule that decides "same" | Value equality (attributes) or identity equality (ID or reference) |
| Value object | Equal by attributes, no identity, immutable | Fowler: "value objects should be immutable"; Evans: "Treat the value object as immutable." |
| Entity (reference object) | Equal by identity, has a lifecycle | Evans DDD Reference: "(aka Reference Objects)" |
| Immutability | No operation changes the object; changes produce a new one | Prevents the aliasing bug (Fowler) |
Language facts we verified: PHP's manual says objects compared with === "are identical if and only if they refer to the same instance of the same class", while == compares attributes of two instances of the same class. Go's spec: "Struct types are comparable if all their field types are comparable", so Money{100, "EUR"} == Money{100, "EUR"} is true, but a struct with a slice field cannot be compared with == at all. Laravel: "The is and isNot methods may be used to quickly verify two models have the same primary key, table, and database connection or not".
Step Code (identity/main.go) Result Why
1 Money{100,"EUR"} == Money{100,"EUR"} true value equality on comparable fields
2 a, b := &Customer{"c-1",old}, &Customer{"c-1",new}
3 a == b false two pointers
4 a.SameAs(b) true same identity (ID)
5 q := p; q.Days[0] = 99; p.Days[0] 99 aliasing: the slice is sharedReal scenario: a date range object shared by two bookings, mutated for one, silently moving the other (Fowler's aliasing bug); duplicate customers created because the code compared entities by e-mail instead of ID; money stored as float and compared with ==, which fails for 0.1 + 0.2.
Fix: Go: value objects as structs with unexported comparable fields and methods that return new values; entities as pointers with an ID and a SameAs method; defensive copies of slices and maps. PHP 8.4: value objects as final readonly class with an equals() method; entities with an ID value object. In Laravel, note that Eloquent's documented value-object cast example mutates the object in place ("any changes made to the value object will automatically be synced back to the model"); with a readonly value object you cannot do that, you assign a new one, which is the point. The DDD treatment is on Entities & Value Objects.
Message passing and Tell-Don't-Ask Important
In plain words: instead of asking an object for its data and deciding for it, tell it what you want and let it decide.
Common misunderstanding: "Tell-Don't-Ask means objects must never return data." Fowler, who explains the principle, warns against exactly that reading: he has seen it turn people into "GetterEradicators", and "there are times when objects collaborate effectively by providing information."
Definition: Fowler's TellDontAsk (2013): "rather than asking an object for data and acting on that data, we should instead tell an object what to do." It is "a principle that helps people remember that object-orientation is about bundling data with the functions that operate on that data." He attributes it to Andy Hunt and Dave Thomas (we did not read their column). It is the practical form of Kay's messaging, and a close relative of the Law of Demeter.
Ask (logic outside the object) Tell (logic inside the object)
1 if order.Status() == Draft && len(order.Lines()) > 0 { err := order.Place(card)
2 receipt, _ := card.Charge(order.Total())
3 order.SetStatus(Placed); order.SetReceipt(receipt)
4 }
5 -- the rule now lives in every caller -- -- the rule lives in Order.Place only --Real scenario: a controller that reads $user->balance, compares it and writes it back, racing with a queued job doing the same; an if ($order->status === 'paid') copied into 14 Blade templates; a Go handler that checks acct.Frozen before every operation instead of acct.Withdraw refusing.
Fix: move the decision into a method named after the intent (Place, Withdraw, Renew). Keep query methods for information others legitimately need (Total(), Status()), and do not chain through objects ($order->customer->address->country), which is the Demeter problem.
Classes, interfaces, traits, mixins and embedding Important
In plain words: these are the different ways a language lets you share either a promise (interface) or code (class inheritance, trait, mixin, embedding) between types.
Common misunderstanding: "Go embedding is inheritance" and "PHP traits are multiple inheritance." Both are composition at compile time with very specific rules, and both differ from inheritance in the way that matters: polymorphism.
Definition:
| Mechanism | Shares | Creates a subtype? | Late binding of self-calls? | Language |
|---|---|---|---|---|
Class (extends) | Code + interface + representation | Yes (nominal) | Yes: overrides affect the base's self-calls | PHP; not Go |
| Interface | Promise only | Yes (PHP nominal, Go structural) | n/a | Both |
| Abstract class | Partial code + promise | Yes | Yes | PHP |
| Trait | Methods and properties copied into the class | No: a trait is not a type | Methods become the class's own | PHP |
| Mixin | Code mixed into a class, usually via inheritance chains | Depends on language | Depends on language | Not in Go or PHP; PHP's manual contrasts traits with "Mixins" |
| Struct embedding | Fields and promoted methods of the inner type | No; but the outer type's method set satisfies interfaces | No: "the receiver of the method is the inner type, not the outer one" | Go |
| Interface embedding | Method sets merged | n/a | n/a | Go (io.ReadWriter) |
The PHP manual: "Traits are a mechanism for code reuse in single inheritance languages such as PHP", and a trait "enables horizontal composition of behavior; that is, the application of class members without requiring inheritance." Its precedence rule: "members from the current class override Trait methods, which in turn override inherited methods." Effective Go: "Go does not provide the typical, type-driven notion of subclassing, but it does have the ability to “borrow” pieces of an implementation by embedding types within a struct or interface."
Call on SMSNotifier (embedding/main.go) Which method runs Output
1 s.Channel() SMSNotifier.Channel (outer, direct) sms
2 s.Send("order 1") promoted Notifier.Send, receiver = inner Notifier
3 Send calls n.Channel() on Notifier [email] order 1
4 Sender{ch: SMS{}}.Send("order 1") composition through an interface [sms] order 1Real scenario: a HasUuid trait on twenty Eloquent models (good: horizontal, stateless reuse); a ManagesBilling trait with 30 methods and its own state that turned the User model into a god object (bad: a trait hides size, it does not remove it); a Go Logger embedded in every service struct, exposing Printf as part of each service's public API by accident.
Fix: interfaces for promises, composition for code, traits only for small stateless helpers that do not need a type, embedding only when you genuinely want the inner type's whole method set on the outer type.
Object lifecycle and construction Good to know
In plain words: an object should be valid from the first moment it exists until it is gone. The constructor is the gate; after it, only methods move the object from one valid state to the next.
Common misunderstanding: "A constructor sets fields; validation happens later in a service." Then an invalid object exists between construction and validation, and every function that receives one must re-check it.
Definition: the lifecycle of an entity is a state machine: created (valid) → transitions through methods → archived or deleted. Construction tools:
| Tool | Go | PHP 8.4 / Laravel | Use when |
|---|---|---|---|
| Constructor | NewOrder(...) (*Order, error) by convention | __construct, possibly private | One obvious way to build it |
| Named constructor | NewDraftOrder, MoneyFromString | static function draft(...) | Several meaningful ways to build it |
| Zero value | Useful zero values are idiomatic (var buf bytes.Buffer) | n/a | The empty state is valid |
| Factory | A function or type that decides which concrete type to return | Factory class; Laravel model factories are for tests | Creation logic is complex or polymorphic: see Creational Patterns |
| Reconstitution | Load from storage without re-running business checks | Eloquent hydration | Data already passed the checks once |
State Allowed transitions (Order) Method
1 (none) -> draft NewOrder / Order::draft
2 draft -> draft (add line) AddLine
3 draft -> placed Place(payment)
4 placed -> cancelled Cancel
5 cancelled (terminal) every mutator returns an errorFix: validate in the constructor or named constructor and return an error (Go) or throw (PHP); make "impossible" states unrepresentable with enums (OrderStatus) instead of strings.
Per-language view
We list only languages whose behaviour we verified in a primary source.
| Language | Encapsulation | Generalization | Polymorphism | Code reuse | Equality |
|---|---|---|---|---|---|
| Simula 67 | Classes, but instances "lack the information-hiding mechanism of data abstractions" (Cardelli and Wegner) | Subclasses inherit the declared entities of superclasses | Virtual procedures (Cardelli and Wegner) | Inheritance | (not covered here) |
| Smalltalk-80 | Enforced at run time; "There cannot be any internal methods in Smalltalk classes" (Liskov 1987) | Classes arranged hierarchically | Methods are called by "sending messages" | Inheritance | (not covered here) |
| CLU | Clusters; encapsulation enforced with compile-time type checking (Liskov 1987) | Not part of the cluster mechanism Liskov describes | Operations belong to the type, not the object | Clusters | Type operations see the reps of several objects at once (adding two integers) |
| Go | Package-level: lowercase identifiers, internal/ | No type hierarchy; implicit interfaces | Structural interfaces; generics (1.18+); type switches | Composition, embedding | == on comparable types |
| PHP 8.4 | private, protected, readonly, asymmetric visibility, hooks | Single extends; multiple implements | Nominal interfaces; no generics; no method overloading | Inheritance, traits, composition | == attributes, === identity |
| Python | (not covered here) | (not covered here) | Duck typing, "complemented with abstract base classes" (Python glossary) | (not covered here) | (not covered here) |
Mechanics
Dynamic dispatch and late binding Important
When a message is sent, something must choose the method. GoF: "The run-time association of a request to an object and one of its operations is known as dynamic binding." Kay's "extreme late-binding of all things" pushes the same choice as late as possible.
| Runtime | How the method is chosen | Cost and consequence |
|---|---|---|
| Go interface call | An interface value is a pair: the Go FAQ says "interfaces are implemented as two elements, a type T and a value V"; the call goes through the dynamic type's method | A nil pointer stored in an interface makes the interface non-nil (the FAQ's "nil error" trap) |
| Go concrete call | Resolved at compile time | No dispatch; inlinable |
| Go generics | Resolved at compile time against the constraint | Type-checked once for all type arguments |
| PHP method call | Looked up on the object's class at run time; class methods beat trait methods, which beat inherited methods | Overrides affect self-calls in the base class (fragile base) |
From sentences to classes: the modeling exercise Must-know
GoF list the classic heuristic among several: "You can write a problem statement, single out the nouns and verbs, and create corresponding classes and operations." (The noun-verb method is usually credited to Russell Abbott's 1983 CACM paper; we did not read it.) It is a starting point. The full method with CRC cards is on The Design Process.
Step 1: domain sentences.
- A customer places an order for one or more products.
- Each order line has a quantity and the unit price at the time of ordering.
- The order total is the sum of its lines, in one currency.
- The customer pays by card or by wallet; a wallet cannot go below zero.
- A placed order can be cancelled; a draft can still be changed.
- The shipping address is copied into the order when it is placed.
Step 2: nouns → candidates, then filter.
| Noun | Decision | Kind | Why |
|---|---|---|---|
| customer | Keep, but outside this model | Entity in another module, referenced by ID | Its lifecycle is not the order's |
| order | Keep | Entity, root of the whole | Has identity and a lifecycle |
| product | Reference only | ID or SKU | Owned by the catalogue |
| order line | Keep | Part (composition) | Dies with the order |
| quantity | Attribute | int with an invariant (> 0) | No behaviour worth a type yet |
| unit price, total | Keep | Money value object | Amount + currency + arithmetic rules |
| currency | Attribute of Money | String code, or enum | Part of a value |
| card, wallet | Keep | Implementations of PaymentMethod | Behave alike, differ inside |
| shipping address | Keep | Address value object, copied | No identity; snapshot at placement |
| time of ordering | Attribute | Timestamp | No behaviour |
Step 3: verbs → operations, placed on the object that owns the data.
| Verb | Operation | Lives on | Rule it protects |
|---|---|---|---|
| places | Place(payment) | Order | Only a non-empty draft can be placed |
| has (lines) | AddLine(sku, qty, price) | Order | Only drafts change; one currency |
| is the sum | Total() | Order (derived) | Total cannot disagree with lines |
| pays | Charge(amount) | PaymentMethod | Each method's own rules (wallet balance) |
| cancelled | Cancel() | Order | Only placed orders |
| copied | constructor argument | Order | Address is a snapshot |
The limits of nouns and verbs. The heuristic finds things the domain talks about; it misses things the design needs. GoF: "object-oriented designs often end up with classes that have no counterparts in the real world", and patterns such as Strategy and State are found "later in the course of making a design more flexible and reusable." It also over-produces: "quantity" and "time" are nouns but not classes. And it ignores change: Parnas's rule (hide what is likely to change) is what decided that payment methods sit behind an interface.
Invariants and where they live Important
| Invariant | Enforced by | Go | PHP 8.4 / Laravel | Database backstop |
|---|---|---|---|---|
| Money is never negative | Value object constructor | NewMoney returns an error | Money::__construct throws | CHECK (unit_price_cents >= 0) |
| Quantity > 0 | Whole's method | AddLine returns ErrBadQuantity | OrderLine::__construct throws | CHECK (quantity > 0) |
| One currency per order | Whole's method | AddLine compares currencies | Order::addLine compares | orders.currency and order_lines.currency + application check |
| Only drafts change | State + method guard | status != Draft → ErrNotDraft | OrderStatus enum check | Optional trigger |
| Total = sum of lines | Derived, not stored | Total() method | Virtual property with a get hook | Do not store, or recompute |
| Lines die with order | Composition | Unexported line, no external constructor | hasMany + cascadeOnDelete | ON DELETE CASCADE |
Go
Before
An anemic model: Order is a bag of exported fields, all rules live in a service, money is a float64, status is a string. The main function shows the result: a float rounding error in the total, a negative quantity accepted, and a typo in the status saved.
// Before: an anemic model. Order is a bag of exported fields and every
// rule lives in a service. Nothing stops callers from building an
// invalid order, so the rules are only as strong as the last caller.
package main
import "fmt"
type Line struct {
SKU string
Qty int
UnitPrice float64 // float money and no currency: two bugs waiting
}
type Order struct {
ID int
Status string // "draft", "placed", ... any string compiles
Lines []Line
Total float64 // stored, so it can disagree with Lines
Customer string
}
type OrderService struct{}
func (OrderService) Place(o *Order) error {
if len(o.Lines) == 0 {
return fmt.Errorf("order %d has no lines", o.ID)
}
o.Total = 0
for _, l := range o.Lines {
o.Total += float64(l.Qty) * l.UnitPrice
}
o.Status = "placed"
return nil
}
func main() {
svc := OrderService{}
o := &Order{ID: 1, Status: "draft", Customer: "c-42"}
o.Lines = append(o.Lines, Line{SKU: "book", Qty: 1, UnitPrice: 0.1})
o.Lines = append(o.Lines, Line{SKU: "pen", Qty: 1, UnitPrice: 0.2})
_ = svc.Place(o)
fmt.Printf("total=%v status=%s\n", o.Total, o.Status)
// Every rule can be bypassed, because the data is public.
o.Lines = append(o.Lines, Line{SKU: "mug", Qty: -3, UnitPrice: 5})
o.Status = "shiped" // typo compiles
fmt.Printf("total=%v status=%s lines=%d\n", o.Total, o.Status, len(o.Lines))
}After
The same domain modelled with the five ideas. Money is a value object; Order is an entity with unexported state and business methods; line is an unexported part created only by the order; PaymentMethod is an interface satisfied structurally by Card and *Wallet.
package ordering
import (
"errors"
"fmt"
)
// Money is a value object: no identity, equal when its fields are equal,
// and immutable (unexported fields, every operation returns a new value).
// Both fields are comparable, so == compares by value.
type Money struct {
cents int64
currency string
}
var ErrCurrencyMismatch = errors.New("currency mismatch")
// NewMoney is the only way to build a Money, so every Money is valid.
func NewMoney(cents int64, currency string) (Money, error) {
if cents < 0 {
return Money{}, fmt.Errorf("negative amount: %d", cents)
}
if len(currency) != 3 {
return Money{}, fmt.Errorf("bad currency: %q", currency)
}
return Money{cents: cents, currency: currency}, nil
}
func (m Money) Add(o Money) (Money, error) {
if m.currency != o.currency {
return Money{}, ErrCurrencyMismatch
}
return Money{cents: m.cents + o.cents, currency: m.currency}, nil
}
func (m Money) Times(n int) Money {
return Money{cents: m.cents * int64(n), currency: m.currency}
}
func (m Money) IsZero() bool { return m.cents == 0 }
func (m Money) String() string {
return fmt.Sprintf("%d.%02d %s", m.cents/100, m.cents%100, m.currency)
}package ordering
import (
"errors"
"fmt"
)
type OrderID string
// Status is a closed set of states; the zero value is Draft.
type Status int
const (
Draft Status = iota
Placed
Cancelled
)
func (s Status) String() string {
return [...]string{"draft", "placed", "cancelled"}[s]
}
// Address is a value object, copied into the order when it is placed.
type Address struct {
Street, City, Country string
}
// line is a part of Order (composition): it has no identity of its own,
// is created only through Order, and dies with it. It is unexported, so
// no other package can hold a line without its order.
type line struct {
sku string
qty int
unit Money
}
var (
ErrNotDraft = errors.New("order is not a draft")
ErrEmptyOrder = errors.New("order has no lines")
ErrBadQuantity = errors.New("quantity must be positive")
ErrCannotCancel = errors.New("only placed orders can be cancelled")
)
// Order is an entity: it has an identity that survives every change of
// its attributes. Fields are unexported; the methods are the only way to
// change state, so the invariants live in one place.
type Order struct {
id OrderID
customerID string // association by identity, not by pointer
status Status
lines []line
shipTo Address
receipt string
}
// NewOrder is the constructor: an Order cannot exist without an id,
// a customer and an address.
func NewOrder(id OrderID, customerID string, shipTo Address) (*Order, error) {
if id == "" || customerID == "" {
return nil, errors.New("id and customer are required")
}
return &Order{id: id, customerID: customerID, shipTo: shipTo}, nil
}
func (o *Order) ID() OrderID { return o.id }
func (o *Order) Status() Status { return o.status }
func (o *Order) Receipt() string { return o.receipt }
func (o *Order) AddLine(sku string, qty int, unit Money) error {
if o.status != Draft {
return ErrNotDraft
}
if qty <= 0 {
return ErrBadQuantity
}
if len(o.lines) > 0 && o.lines[0].unit.currency != unit.currency {
return ErrCurrencyMismatch
}
o.lines = append(o.lines, line{sku: sku, qty: qty, unit: unit})
return nil
}
// Total is derived, never stored, so it cannot disagree with the lines.
func (o *Order) Total() Money {
if len(o.lines) == 0 {
return Money{}
}
total := Money{currency: o.lines[0].unit.currency}
for _, l := range o.lines {
total, _ = total.Add(l.unit.Times(l.qty)) // same currency by invariant
}
return total
}
// Place is "tell, don't ask": the caller tells the order to place itself
// and hands it a payment method; the order decides whether it may.
func (o *Order) Place(pay PaymentMethod) error {
if o.status != Draft {
return ErrNotDraft
}
if len(o.lines) == 0 {
return ErrEmptyOrder
}
receipt, err := pay.Charge(o.Total())
if err != nil {
return fmt.Errorf("place %s: %w", o.id, err)
}
o.receipt = receipt
o.status = Placed
return nil
}
func (o *Order) Cancel() error {
if o.status != Placed {
return ErrCannotCancel
}
o.status = Cancelled
return nil
}package ordering
import (
"errors"
"fmt"
)
// PaymentMethod is the abstraction the Order depends on. Any type with a
// Charge method satisfies it (structural typing: no "implements").
type PaymentMethod interface {
Charge(amount Money) (receipt string, err error)
}
type Card struct{ Last4 string }
func (c Card) Charge(amount Money) (string, error) {
return fmt.Sprintf("card *%s charged %s", c.Last4, amount), nil
}
// Wallet has state, so it uses a pointer receiver.
type Wallet struct{ balance Money }
func NewWallet(balance Money) *Wallet { return &Wallet{balance: balance} }
var ErrInsufficientFunds = errors.New("insufficient funds")
func (w *Wallet) Charge(amount Money) (string, error) {
if w.balance.currency != amount.currency || w.balance.cents < amount.cents {
return "", ErrInsufficientFunds
}
w.balance = Money{cents: w.balance.cents - amount.cents, currency: w.balance.currency}
return fmt.Sprintf("wallet charged %s, left %s", amount, w.balance), nil
}package main
import (
"errors"
"fmt"
"academy/oop-modeling-fundamentals/after/ordering"
)
func main() {
eur := func(c int64) ordering.Money { m, _ := ordering.NewMoney(c, "EUR"); return m }
o, _ := ordering.NewOrder("o-1", "c-42", ordering.Address{Street: "Main St 1", City: "Berlin", Country: "DE"})
_ = o.AddLine("book", 2, eur(1000))
_ = o.AddLine("pen", 1, eur(250))
fmt.Println("total:", o.Total())
fmt.Println("bad qty:", o.AddLine("mug", -3, eur(500)))
usd, _ := ordering.NewMoney(500, "USD")
fmt.Println("mixed currency:", o.AddLine("mug", 1, usd))
err := o.Place(ordering.NewWallet(eur(1500)))
fmt.Println("wallet:", err, errors.Is(err, ordering.ErrInsufficientFunds))
if err := o.Place(ordering.Card{Last4: "4242"}); err == nil {
fmt.Println("placed:", o.Status(), o.Receipt())
}
fmt.Println("add after place:", o.AddLine("mug", 1, eur(500)))
fmt.Println("cancel:", o.Cancel(), o.Status())
// o.status = ordering.Cancelled // does not compile: unexported field
}The Go angle
The Go FAQ answers "Is Go an object-oriented language?" with "Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy." What Go gives you instead:
| Idea | Go tool | Note |
|---|---|---|
| Abstraction | Small interfaces, often one method (io.Writer) | Effective Go: "Interfaces with only one or two methods are common in Go code" |
| Encapsulation | Unexported identifiers; the package is the boundary | Code in the same package can touch unexported fields, so keep packages small |
| Decomposition | Struct fields; unexported part types | Hold other entities by ID |
| Generalization | Implicit interfaces | "Interfaces can be added after the fact if a new idea comes along or for testing—without annotating the original types" (Go FAQ) |
| Polymorphism | Interfaces, generics, type switches | A common guideline: accept interfaces, return concrete types |
| Code reuse | Embedding and composition | Embedding is not subclassing |
Embedding, polymorphism and identity, each as a runnable program:
// Embedding is not subclassing. A promoted method runs with the inner
// type as its receiver, so there is no "override" through self-calls.
package main
import "fmt"
type Notifier struct{}
func (Notifier) Channel() string { return "email" }
// Send calls Channel on Notifier, never on an outer type.
func (n Notifier) Send(msg string) string {
return fmt.Sprintf("[%s] %s", n.Channel(), msg)
}
// SMSNotifier embeds Notifier and "redefines" Channel.
type SMSNotifier struct {
Notifier
}
func (SMSNotifier) Channel() string { return "sms" }
// Composition with an explicit dependency gives the variation on purpose.
type Channel interface{ Name() string }
type SMS struct{}
func (SMS) Name() string { return "sms" }
type Sender struct{ ch Channel }
func (s Sender) Send(msg string) string {
return fmt.Sprintf("[%s] %s", s.ch.Name(), msg)
}
func main() {
s := SMSNotifier{}
fmt.Println(s.Channel()) // sms: the outer method wins for direct calls
fmt.Println(s.Send("order 1")) // [email]: Send's receiver is the inner Notifier
fmt.Println(Sender{ch: SMS{}}.Send("order 1")) // [sms]: variation by composition
}// Three kinds of polymorphism in Go: subtype (interfaces, structural),
// parametric (generics) and ad hoc (type switch; Go has no overloading).
package main
import (
"cmp"
"fmt"
"strconv"
)
// Subtype polymorphism: any type with Area() is a Shape. Neither type
// below mentions Shape; the compiler checks the method set.
type Shape interface{ Area() float64 }
type Rect struct{ W, H float64 }
type Circle struct{ R float64 }
func (r Rect) Area() float64 { return r.W * r.H }
func (c Circle) Area() float64 { return 3.14159 * c.R * c.R }
func TotalArea(shapes ...Shape) float64 {
var sum float64
for _, s := range shapes {
sum += s.Area() // dynamic dispatch through the interface value
}
return sum
}
// Parametric polymorphism: one body, any ordered type, checked at compile time.
func Max[T cmp.Ordered](xs ...T) T {
m := xs[0]
for _, x := range xs[1:] {
m = max(m, x)
}
return m
}
// A generic container: the type parameter is part of the type.
type Stack[T any] struct{ items []T }
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
func (s *Stack[T]) Pop() (T, bool) {
var zero T
if len(s.items) == 0 {
return zero, false
}
v := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return v, true
}
// Ad hoc polymorphism: different code per type, chosen by a type switch.
func Describe(v any) string {
switch x := v.(type) {
case int:
return "int " + strconv.Itoa(x)
case string:
return "string " + strconv.Quote(x)
case Shape:
return fmt.Sprintf("shape with area %.1f", x.Area())
default:
return fmt.Sprintf("unknown %T", x)
}
}
func main() {
fmt.Printf("%.2f\n", TotalArea(Rect{2, 3}, Circle{1}))
fmt.Println(Max(3, 9, 4), Max("pear", "apple"))
var s Stack[string]
s.Push("a")
s.Push("b")
top, _ := s.Pop()
fmt.Println(top)
fmt.Println(Describe(7), "|", Describe("x"), "|", Describe(Rect{1, 2}), "|", Describe(1.5))
}// Identity, equality and the aliasing bug.
package main
import "fmt"
// Value object: comparable fields, so == means "same value".
type Money struct {
Cents int64
Currency string
}
// Entity: equality is identity (the ID), not the attributes.
type Customer struct {
ID string
Email string
}
func (c *Customer) SameAs(o *Customer) bool { return c.ID == o.ID }
// A mutable "value" shared by reference: the aliasing bug.
type Period struct{ Days []int }
func main() {
fmt.Println(Money{100, "EUR"} == Money{100, "EUR"}) // true: value equality
a := &Customer{ID: "c-1", Email: "old@example.com"}
b := &Customer{ID: "c-1", Email: "new@example.com"}
fmt.Println(a == b, a.SameAs(b)) // false true: two pointers, one identity
p := Period{Days: []int{1, 2, 3}}
q := p // copies the struct, but both share the slice's backing array
q.Days[0] = 99
fmt.Println(p.Days[0]) // 99: p changed through q
r := Period{Days: append([]int(nil), p.Days...)} // defensive copy
r.Days[0] = 1
fmt.Println(p.Days[0], r.Days[0]) // 99 1
}In production: the standard library uses exactly this. Effective Go shows bufio.ReadWriter, a struct that embeds *Reader and *Writer and so satisfies io.ReadWriter with no forwarding methods; and when its Read runs, "the receiver is the reader field of the ReadWriter, not the ReadWriter itself."
Two Go-specific traps. First, a method with a value receiver on a type that holds a slice still shares the backing array (the Period example), so "value" does not imply "immutable". Second, encoding/json ignores unexported fields, so a well-encapsulated entity marshals to {}: that is the language telling you to map it to a DTO (see microservices).
Laravel
Before
An anemic Eloquent model marked #[Unguarded] (every attribute mass-assignable), a float total, a free-text status and a service that anyone can skip with Order::create([...]) or $order->update([...]).
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Unguarded;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
// Before: an anemic model. The Eloquent model is a bag of attributes,
// every column is mass-assignable, status is a free string, money is a
// float, and all behaviour lives in a service that anyone can bypass.
#[Unguarded]
class Order extends Model
{
public function lines(): HasMany
{
return $this->hasMany(OrderLine::class);
}
}
#[Unguarded]
class OrderLine extends Model
{
}
namespace App\Services;
use App\Models\Order;
use RuntimeException;
class OrderService
{
public function place(Order $order): void
{
if ($order->lines()->count() === 0) {
throw new RuntimeException('Order has no lines.');
}
$total = 0.0;
foreach ($order->lines as $line) {
$total += $line->qty * $line->unit_price; // float money
}
$order->total = $total; // stored, can drift from the lines
$order->status = 'placed'; // any string is accepted
$order->save();
}
}
// Elsewhere, nothing stops this:
// Order::create(['status' => 'shiped', 'total' => -5]);
// $order->update(['status' => 'draft']); // un-place a paid orderAfter
First the pure PHP 8.4 domain model: readonly value objects, a backed enum with behaviour, an entity with private(set) state and a virtual total property, a PaymentMethod interface, and a trait for event recording.
<?php
namespace App\Domain\Ordering;
use DomainException;
use InvalidArgumentException;
// Value object (PHP 8.2 readonly class): no identity, immutable,
// compared by value. Every operation returns a new instance.
final readonly class Money
{
public function __construct(public int $cents, public string $currency)
{
if ($cents < 0) {
throw new InvalidArgumentException("Negative amount: {$cents}");
}
if (strlen($currency) !== 3) {
throw new InvalidArgumentException("Bad currency: {$currency}");
}
}
public static function zero(string $currency): self
{
return new self(0, $currency);
}
public function add(Money $other): self
{
if ($other->currency !== $this->currency) {
throw new DomainException('Currency mismatch.');
}
return new self($this->cents + $other->cents, $this->currency);
}
public function times(int $n): self
{
return new self($this->cents * $n, $this->currency);
}
public function equals(Money $other): bool
{
return $this->cents === $other->cents && $this->currency === $other->currency;
}
}
final readonly class OrderId
{
public function __construct(public string $value)
{
if ($value === '') {
throw new InvalidArgumentException('Order id is required.');
}
}
public function equals(OrderId $other): bool
{
return $this->value === $other->value;
}
}
final readonly class Address
{
public function __construct(
public string $street,
public string $city,
public string $country,
) {}
}
// A closed set of states (PHP 8.1 backed enum) with behaviour on it.
enum OrderStatus: string
{
case Draft = 'draft';
case Placed = 'placed';
case Cancelled = 'cancelled';
public function canCancel(): bool
{
return $this === self::Placed;
}
}
// Part of an Order (composition): created only by Order::addLine().
final readonly class OrderLine
{
public function __construct(
public string $sku,
public int $quantity,
public Money $unitPrice,
) {
if ($quantity <= 0) {
throw new DomainException('Quantity must be positive.');
}
}
public function subtotal(): Money
{
return $this->unitPrice->times($this->quantity);
}
}
// Polymorphism through an interface (nominal: classes must say "implements").
interface PaymentMethod
{
/** Charges the amount and returns a receipt reference. */
public function charge(Money $amount): string;
}
final class CardPayment implements PaymentMethod
{
public function __construct(private string $last4) {}
public function charge(Money $amount): string
{
return "card *{$this->last4} charged {$amount->cents} {$amount->currency}";
}
}
final class WalletPayment implements PaymentMethod
{
// PHP 8.4 asymmetric visibility: readable outside, writable only inside.
public function __construct(public private(set) Money $balance) {}
public function charge(Money $amount): string
{
if ($amount->currency !== $this->balance->currency || $amount->cents > $this->balance->cents) {
throw new DomainException('Insufficient funds.');
}
$this->balance = new Money($this->balance->cents - $amount->cents, $amount->currency);
return "wallet charged {$amount->cents}";
}
}
final readonly class OrderPlaced
{
public function __construct(public OrderId $orderId, public Money $total) {}
}
// Horizontal reuse without a base class: any aggregate can record events.
trait RecordsEvents
{
/** @var list<object> */
private array $recordedEvents = [];
protected function record(object $event): void
{
$this->recordedEvents[] = $event;
}
/** @return list<object> */
public function releaseEvents(): array
{
[$events, $this->recordedEvents] = [$this->recordedEvents, []];
return $events;
}
}
// Entity: identity (OrderId) plus a lifecycle. State changes only through
// methods that protect the invariants; outsiders can read, not write.
final class Order
{
use RecordsEvents;
public private(set) OrderStatus $status;
public private(set) ?string $receipt = null;
/** @var list<OrderLine> */
private array $lines = [];
// PHP 8.4 virtual property: a get hook with no backing value.
public Money $total {
get => array_reduce(
$this->lines,
fn (Money $sum, OrderLine $line) => $sum->add($line->subtotal()),
Money::zero($this->currency),
);
}
private function __construct(
public readonly OrderId $id,
public readonly string $customerId,
public readonly Address $shipTo,
private readonly string $currency,
) {
$this->status = OrderStatus::Draft;
}
// Named constructor: the only way to start an order's lifecycle.
public static function draft(OrderId $id, string $customerId, Address $shipTo, string $currency): self
{
return new self($id, $customerId, $shipTo, $currency);
}
public function addLine(string $sku, int $quantity, Money $unitPrice): void
{
if ($this->status !== OrderStatus::Draft) {
throw new DomainException('Order is not a draft.');
}
if ($unitPrice->currency !== $this->currency) {
throw new DomainException('Currency mismatch.');
}
$this->lines[] = new OrderLine($sku, $quantity, $unitPrice);
}
// Tell, don't ask: the order decides whether it may be placed.
public function place(PaymentMethod $payment): void
{
if ($this->status !== OrderStatus::Draft) {
throw new DomainException('Order is not a draft.');
}
if ($this->lines === []) {
throw new DomainException('Order has no lines.');
}
$this->receipt = $payment->charge($this->total);
$this->status = OrderStatus::Placed;
$this->record(new OrderPlaced($this->id, $this->total));
}
public function cancel(): void
{
if (! $this->status->canCancel()) {
throw new DomainException('Only placed orders can be cancelled.');
}
$this->status = OrderStatus::Cancelled;
}
/** @return list<OrderLine> Lines are readonly values, so sharing them is safe. */
public function lines(): array
{
return $this->lines;
}
}Then the same rules on an Eloquent model, which is how most Laravel 13 applications will write it: a custom cast turns two columns into a Money value object, the enum cast closes the set of statuses, the Laravel 13 #[Fillable] attribute leaves status out, and the transitions are methods.
<?php
namespace App\Casts;
use App\Domain\Ordering\Money;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
// Maps two columns (unit_price_cents, currency) to one Money value object.
class AsMoney implements CastsAttributes
{
public function get(Model $model, string $key, mixed $value, array $attributes): Money
{
return new Money((int) $attributes['unit_price_cents'], $attributes['currency']);
}
public function set(Model $model, string $key, mixed $value, array $attributes): array
{
if (! $value instanceof Money) {
throw new InvalidArgumentException('The given value is not a Money instance.');
}
return ['unit_price_cents' => $value->cents, 'currency' => $value->currency];
}
}
namespace App\Models;
use App\Casts\AsMoney;
use App\Domain\Ordering\Money;
use App\Domain\Ordering\OrderStatus;
use App\Domain\Ordering\PaymentMethod;
use App\Events\OrderPlaced;
use DomainException;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\DB;
// The Laravel entity: an Eloquent model that keeps its own rules.
// Identity is the primary key ($order->is($other) compares key, table and connection).
// status and receipt are not fillable: only the methods below change them.
#[Fillable(['customer_id', 'currency'])]
class Order extends Model
{
protected $attributes = ['status' => 'draft'];
protected function casts(): array
{
return ['status' => OrderStatus::class];
}
// Association: the customer lives on without this order.
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class);
}
// Composition: lines are created through the order and deleted with it
// (the migration uses cascadeOnDelete on order_lines.order_id).
public function lines(): HasMany
{
return $this->hasMany(OrderLine::class);
}
public function addLine(string $sku, int $quantity, Money $unitPrice): OrderLine
{
if ($this->status !== OrderStatus::Draft) {
throw new DomainException('Order is not a draft.');
}
if ($quantity <= 0 || $unitPrice->currency !== $this->currency) {
throw new DomainException('Invalid line.');
}
return $this->lines()->create(['sku' => $sku, 'quantity' => $quantity, 'unit_price' => $unitPrice]);
}
// Derived, never stored: it cannot drift from the lines.
public function total(): Money
{
return $this->lines->reduce(
fn (Money $sum, OrderLine $line) => $sum->add($line->unit_price->times($line->quantity)),
Money::zero($this->currency),
);
}
public function place(PaymentMethod $payment): void
{
DB::transaction(function () use ($payment) {
$order = static::query()->lockForUpdate()->findOrFail($this->getKey());
if ($order->status !== OrderStatus::Draft || $order->lines()->doesntExist()) {
throw new DomainException('Order cannot be placed.');
}
$this->receipt = $payment->charge($this->total());
$this->status = OrderStatus::Placed;
$this->save();
OrderPlaced::dispatch($this->getKey());
});
}
}
#[Fillable(['sku', 'quantity', 'unit_price'])]
class OrderLine extends Model
{
protected function casts(): array
{
// A readonly Money cannot be edited in place: assign a new one.
return ['unit_price' => AsMoney::class, 'quantity' => 'integer'];
}
}The Laravel angle
| Idea | Laravel 13 / PHP 8.4 tool | Note |
|---|---|---|
| Value object | final readonly class + custom cast (CastsAttributes) | Multi-column casts return an array of columns from set() (Laravel docs) |
| Closed set of states | Backed enum + enum cast in casts() | Behaviour on the enum (canCancel()) |
| Encapsulation on Eloquent | #[Fillable] attribute without state columns; transition methods | Eloquent attributes are magic, so private(set) cannot protect them; methods must |
| Entity identity | Primary key; $a->is($b) | Compares key, table and connection |
| Composition | hasMany + cascadeOnDelete() in the migration | Create parts through the whole |
| Association | belongsTo, belongsToMany | Do not save the other side from here |
| Polymorphism | Interfaces bound in the service container | $this->app->bind(PaymentMethod::class, ...) |
| Code reuse | Traits (HasUuids, SoftDeletes, your own) | Keep them small and stateless |
| Boundaries | Form Requests (in), API Resources (out), event DTOs | Never return the model as the contract |
A readonly value object and Eloquent's cast caching fit together if you treat the value as replaceable: $line->unit_price = $line->unit_price->times(2) assigns a new Money, the cast's set() writes the two columns, and nothing is mutated in place.
Solving the classic problems
| Problem | Symptom | Solution | How | Cost / limitation |
|---|---|---|---|---|
| Anemic domain model | Getters/setters only; rules in services | Move rules into the objects that own the data | Tell-Don't-Ask, private state, methods named after actions | Mapping to storage is more work |
| God object | One class every feature touches | Split by responsibility and by whole-part | Extract Class, value objects, separate entities | More classes and names |
| Deep hierarchy | 4+ levels of extends; overrides of overrides | Flatten to interfaces + composition | Replace Subclass with Delegate (Fowler's catalogue) | Some forwarding code |
| Inheritance for code reuse | extends BaseService to get helpers | Composition or a small trait | Inject the helper; forward | A constructor parameter |
| Primitive obsession | float $price, string $status everywhere | Value objects and enums | Money, OrderStatus | Conversions at the edges |
| Setter for everything | setStatus(), setTotal() | Transition methods + derived values | place(), cancel(), Total() | Fewer "flexible" APIs, on purpose |
| Leaking model at the boundary | Model serialised as API/event | DTOs and Resources | Explicit mappers | One more type per contract |
Anemic domain model
Fowler: "The fundamental horror of this anti-pattern is that it's so contrary to the basic idea of object-oriented design; which is to combine data and process together." He is equally clear that a thin service layer on top of a rich model is fine: the problem is a model where "there is hardly any behavior on these objects". The Go before/after and the Laravel before/after are this refactoring. The step-by-step move:
Step Move Example
1 find a rule in a service that reads and writes one object's fields OrderService.Place sets o.Total, o.Status
2 move it to a method on that object (Move Function) Order.Place(pay)
3 make the fields it writes private, add read-only accessors status unexported, Status() getter
4 delete the setters; fix every caller to use the new method o.Status = ... no longer compiles
5 repeat; the service shrinks to orchestration (load, call, save, publish)The full DDD discussion, including when a transaction script is the better choice, is on Anemic vs Rich Domain Models.
God object
A god object (also "god class"; the term is widely used in the code-smell literature, and its exact origin is not settled in the sources we read) knows and does too much. In modeling terms it is a decomposition failure: several wholes and parts crammed into one class. Split it along the relationships from Decomposition: value objects for groups of attributes (Address, Money, Period), separate entities for things with their own lifecycle (BillingProfile), and parts owned by the right whole. The responsibility view of the same problem is on SRP; the smell catalogue is on Code Smells & Refactoring.
Deep hierarchies
Animal → Mammal → Dog → ServiceDog → GuideDog reads well and changes badly: every level adds overrides, and the behaviour of a leaf depends on five files. Flatten by asking, for each level, "is this a real is-a that callers rely on, or is it code reuse?" Keep the interfaces callers use, turn the rest into composed parts (Dog{trainer Trainer, harness Harness}), and make concrete classes final.
Inheritance for code reuse
The PHP version of the fragile base class timeline and its fix: the first half extends a base class and double-counts; the second half composes the same behaviour behind an interface and is immune to how the inner object is written.
<?php
namespace App\Support;
// Version 1 of a base class shipped in a shared package.
class TagSet
{
/** @var array<string, true> */
protected array $tags = [];
public function add(string $tag): void
{
$this->tags[$tag] = true;
}
public function addMany(array $tags): void
{
foreach ($tags as $tag) {
$this->add($tag); // self-call: subclasses that override add() are involved
}
}
public function count(): int
{
return count($this->tags);
}
}
// A subclass in an application that reuses TagSet by inheritance.
class CountingTagSet extends TagSet
{
public int $attempts = 0;
public function add(string $tag): void
{
$this->attempts++;
parent::add($tag);
}
public function addMany(array $tags): void
{
$this->attempts += count($tags);
parent::addMany($tags); // calls add() again: every tag is counted twice
}
}
// (new CountingTagSet)->addMany(['a', 'b']) gives attempts = 4, not 2.
// Deleting the addMany() override "fixes" it (2), but now the count relies on
// the base class calling add() for each tag. When a later version of the base
// class writes $this->tags directly (a "safe" optimisation), attempts drops
// to 0 although nobody touched the subclass. That is the fragile base class.
namespace App\Support\Composed;
interface Tags
{
public function add(string $tag): void;
public function addMany(array $tags): void;
public function count(): int;
}
final class TagSet implements Tags
{
/** @var array<string, true> */
private array $tags = [];
public function add(string $tag): void
{
$this->tags[$tag] = true;
}
public function addMany(array $tags): void
{
foreach ($tags as $tag) {
$this->tags[$tag] = true;
}
}
public function count(): int
{
return count($this->tags);
}
}
// Composition + forwarding: depends only on the Tags interface, so how the
// inner object implements addMany() can change without affecting the count.
final class CountingTags implements Tags
{
public private(set) int $attempts = 0;
public function __construct(private Tags $inner) {}
public function add(string $tag): void
{
$this->attempts++;
$this->inner->add($tag);
}
public function addMany(array $tags): void
{
$this->attempts += count($tags);
$this->inner->addMany($tags);
}
public function count(): int
{
return $this->inner->count();
}
}Primitive obsession and setters for everything
// Before: three primitives and two setters; any combination compiles.
$order->setTotal(19.99);
$order->setCurrency('eur');
$order->setStatus('placed');
// After: one value object, one transition.
$order->place(new CardPayment('4242')); // total is derived as Money, status is an enum// Before
o.Total, o.Currency, o.Status = 19.99, "eur", "placed"
// After
err := o.Place(Card{Last4: "4242"})Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Many interchangeable implementations of one capability | Interface + one class per implementation | Container binding (Laravel), constructor injection (Go) | Subtype polymorphism; new types are cheap |
| Same algorithm for many types | Generics (Go); a typed collection class (PHP) | Constraints (cmp.Ordered, comparable) | Parametric polymorphism; one body |
| Closed, small set of variants, many operations | Enum + match / switch | Exhaustiveness via tests or static analysis | Data-structure style: new operations are cheap |
| Need another object's code, not its type | Composition + delegation | Forward only what you use | Black-box reuse; no fragile base |
| Small stateless helper on many classes | PHP trait; Go function or embedded helper | Keep it under a screenful | Horizontal reuse without hierarchy |
| A real, stable "is-a" that callers rely on | extends (PHP) with final leaves | Contract tests (LSP) | Shares representation legitimately |
Framework requires a base class (Eloquent Model, FormRequest) | Extend it, keep domain rules in your own types | Read upgrade guides | You do not own the base class |
| Thing defined by its attributes | Value object, immutable | equals(); == in Go | No identity to track |
| Thing with identity and lifecycle | Entity with transition methods | State enum | Rules live in one place |
| Data crossing a process boundary | DTO / data structure | Versioned, explicit mapper | Contracts change on purpose, not by accident |
In architecture: from a single process to a distributed system
An object model is a promise that holds inside one address space: references are cheap, method calls cannot be lost, and encapsulation is enforced by the compiler. Each step outward removes one of those promises, and the model has to give something up.
Monolith: one process, one database
How it shows up: classes and their relationships are the architecture. The failures are the anemic model, the god object and the Eloquent model returned directly as JSON.
Simplest correct usage: a rich model for the parts with real rules (orders, payments, subscriptions), plain CRUD for the parts without (settings pages), value objects everywhere money, time ranges, addresses and quantities appear.
Example (simple): a blog: Post with publish() and unpublish() methods, a Slug value object, an enum PostStatus. The controller calls $post->publish(), never $post->status = 'published'.
Example (complex): the shop on this page. Order composes OrderLines, associates a customer by ID, uses Money and Address value objects, and depends on PaymentMethod. One database transaction covers the whole aggregate.
Modular monolith and multiple databases
How it shows up: each module (Ordering, Catalog, Billing) owns its object model. Another module's objects are not parts of yours: you hold them by ID, and you ask the other module through its public interface.
Ordering module Catalog module (public interface only)
1 order.AddLine(sku, qty, price) <- catalog.PriceFor(sku) returns Money
2 Order never holds a *catalog.Product pointer; only the SKU string
3 Catalog renames Product.price to Product.listPrice: Ordering does not noticeRules: association across modules is by ID only; value objects such as Money can live in a small shared kernel because they have no identity and no lifecycle; no module's entities are passed into another module's methods. Database-wise, one schema per module (Modular Monolith covers enforcement).
Microservices: object model vs service contracts
What survives: abstraction (a service is an abstraction with an API), encapsulation (the database is private to the service), polymorphism at the contract level (any service that speaks the contract can replace another). What does not: object identity across services, references, method calls that cannot fail, shared classes. A *Order pointer cannot cross the network; only data can.
The picture shows the Ordering service on the left with its own object model (entity, value object, parts), an explicit mapper that produces a versioned OrderPlacedV1 DTO, the DTO crossing the broker or HTTP in the middle, and the Billing service on the right mapping it into its own Invoice model. No class is shared; only the contract is.
This is exactly where Fowler's Data Transfer Object belongs: "An object that carries data between processes in order to reduce the number of method calls." His LocalDTO note is the other half: in a local context DTOs "are actually harmful", so do not introduce them between layers of one process unless there is a boundary.
// At a service boundary the object model stays inside; a versioned,
// behaviour-free contract (a DTO) crosses the wire.
package main
import (
"encoding/json"
"fmt"
"time"
)
// Domain side (simplified): unexported state, behaviour on methods.
type Order struct {
id string
customerID string
totalCents int64
currency string
placedAt time.Time
}
func (o Order) ID() string { return o.id }
// OrderPlacedV1 is the published contract: a data structure, not an
// object. Field names, types and the version are a promise to consumers.
type OrderPlacedV1 struct {
Version int `json:"version"`
OrderID string `json:"order_id"`
CustomerID string `json:"customer_id"`
Total struct {
Cents int64 `json:"cents"`
Currency string `json:"currency"`
} `json:"total"`
PlacedAt time.Time `json:"placed_at"`
}
// ToOrderPlacedV1 is the explicit mapping. Renaming a domain field does
// not change the contract; changing the contract is a visible decision.
func ToOrderPlacedV1(o Order) OrderPlacedV1 {
e := OrderPlacedV1{Version: 1, OrderID: o.id, CustomerID: o.customerID, PlacedAt: o.placedAt}
e.Total.Cents = o.totalCents
e.Total.Currency = o.currency
return e
}
func main() {
o := Order{id: "o-1", customerID: "c-42", totalCents: 2250, currency: "EUR",
placedAt: time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)}
b, _ := json.Marshal(ToOrderPlacedV1(o))
fmt.Println(string(b))
// json.Marshal(o) would print {} because the fields are unexported:
// encapsulation and serialization pull in opposite directions.
raw, _ := json.Marshal(o)
fmt.Println(string(raw))
}<?php
namespace App\Contracts\Events;
use App\Models\Order;
// The published contract: a data structure (DTO), versioned, no behaviour.
// Consumers in other services depend on this shape, never on App\Models\Order.
final readonly class OrderPlacedV1
{
public function __construct(
public string $orderId,
public string $customerId,
public int $totalCents,
public string $currency,
public string $placedAt,
public int $version = 1,
) {}
public static function fromOrder(Order $order): self
{
$total = $order->total();
return new self(
orderId: (string) $order->getKey(),
customerId: (string) $order->customer_id,
totalCents: $total->cents,
currency: $total->currency,
placedAt: $order->updated_at->toIso8601String(),
);
}
/** @return array<string, int|string> */
public function toArray(): array
{
return get_object_vars($this);
}
}
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
// Inbound boundary: validation of the outside world's data structure.
class PlaceOrderRequest extends FormRequest
{
public function rules(): array
{
return [
'payment.type' => ['required', 'in:card,wallet'],
'payment.last4' => ['required_if:payment.type,card', 'digits:4'],
];
}
}
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
// Outbound boundary for HTTP: the JSON shape is chosen here, not by the model.
class OrderResource extends JsonResource
{
public function toArray(Request $request): array
{
$total = $this->total();
return [
'id' => $this->id,
'status' => $this->status->value,
'total' => ['cents' => $total->cents, 'currency' => $total->currency],
];
}
}
namespace App\Http\Controllers;
use App\Domain\Ordering\CardPayment;
use App\Http\Requests\PlaceOrderRequest;
use App\Http\Resources\OrderResource;
use App\Models\Order;
class PlaceOrderController
{
public function __invoke(PlaceOrderRequest $request, Order $order): OrderResource
{
// Translate the outside data structure into an object, then tell the entity.
$order->place(new CardPayment($request->validated()['payment']['last4']));
return new OrderResource($order->load('lines'));
}
} Step Ordering service Broker / network Billing service
1 order.Place(card) in a DB transaction
2 write OrderPlacedV1 to the outbox, same transaction
3 relay publishes the outbox row -> orders.placed (v1)
4 -> map v1 to its Invoice entity
5 renames Order.customerID to buyerID: mapper changes, contract does not; Billing never noticesReliable publishing is the outbox pattern; evolving OrderPlacedV1 into V2 without breaking consumers is Message Design & Schema Evolution; where to draw the boundaries is Bounded Context.
Distributed data: replicas, caches and serialised objects
Where the object model breaks: identity becomes a convention (two services both cache "order o-1" and disagree), immutability becomes valuable (an immutable value can be cached and replicated without coordination; a mutable entity cannot), and encapsulation leaks through serialisation (PHP serialize() or Go gob of an entity into Redis couples the cache format to private fields).
| Concern | Object-model answer | Distributed answer |
|---|---|---|
| Identity | Reference or ID in memory | Globally unique IDs (UUID, ULID); see ID generation in the database section |
| Equality | equals() / == | Compare IDs and versions; last-writer-wins needs a clock |
| Mutation | Methods change state | Commands to the owning service; events for everyone else |
| Caching | Object in memory | Cache DTOs or value objects, never entities with behaviour |
| Replication | n/a | Replica reads may show an older state of the entity |
Countermeasures: cache data structures with a version field, not serialised objects; make cached and replicated things immutable values; keep one writer per entity.
Scaling path: 1×, 10×, 100×
| Scale | Structure | Modeling practice |
|---|---|---|
| 1× (one team, one app) | Rich model where rules exist, CRUD elsewhere | Value objects, enums, transition methods |
| 10× (several teams, one repository) | Modular monolith, one model per module | Cross-module references by ID; shared kernel only for value objects |
| 100× (many services) | Services per bounded context | Object model private to each service; versioned DTO contracts; events |
Lab
You run the Go programs, then break and fix the model. Everything runs offline with Go 1.24 or newer.
Setup.
cd docs/snippets/design/oop-modeling-fundamentals/go
gofmt -l . && go vet ./... # no output: formatted and vet-cleanExperiment 1: the anemic model lets anything in.
go run ./before
# total=0.30000000000000004 status=placed
# total=0.30000000000000004 status=shiped lines=3Expected: a float rounding error in money, a negative quantity accepted, a misspelt status stored, and a total that no longer matches the lines.
Experiment 2: the encapsulated model refuses.
go run ./after
# total: 22.50 EUR
# bad qty: quantity must be positive
# mixed currency: currency mismatch
# wallet: place o-1: insufficient funds true
# placed: placed card *4242 charged 22.50 EUR
# add after place: order is not a draft
# cancel: <nil> cancelledThe domain lives in its own package, after/ordering, as it would in a real application. Uncomment the last line of after/main.go (o.status = ordering.Cancelled) and build. Expected: o.status undefined (type *ordering.Order has no field or method status, but does have method Status). In Go the encapsulation boundary is the package, not the type: code inside ordering can still touch status, so keep domain packages small.
Experiment 3: embedding is not subclassing.
go run ./embedding
# sms
# [email] order 1
# [sms] order 1Explain line 2 using Effective Go's rule ("the receiver of the method is the inner type, not the outer one"), then make Sender print [email] by passing a new Email type: no existing code changes.
Experiment 4: three kinds of polymorphism.
go run ./polymorphism
# 9.14
# 9 pear
# b
# int 7 | string "x" | shape with area 2.0 | unknown float64Add a Triangle with Area(): TotalArea and Describe's Shape branch accept it with no edits. Now add a Perimeter() requirement to Shape: every existing shape breaks. That is the objects-vs-data-structures trade-off in two minutes.
Experiment 5: identity and aliasing.
go run ./identity
# true
# false true
# 99
# 99 1Change Money to hold a []string of tags and try ==: expected compile error invalid operation: Money{} == Money{} (struct containing []string cannot be compared).
Experiment 6: the boundary.
go run ./boundary
# {"version":1,"order_id":"o-1","customer_id":"c-42","total":{"cents":2250,"currency":"EUR"},"placed_at":"2026-11-25T10:00:00Z"}
# {}Rename the domain field customerID to buyerID and fix the mapper: the JSON is unchanged.
Experiment 7 (Laravel, read-through). In a Laravel 13 app with the Eloquent.php models and a migration using cascadeOnDelete(): Order::create(['customer_id' => 1, 'currency' => 'EUR', 'status' => 'placed']) ignores status (not fillable) and the order starts as draft; $order->addLine('book', 0, new Money(1000, 'EUR')) throws DomainException; deleting the order deletes its lines; deleting a customer with orders fails on the foreign key.
Common misconceptions
| Belief | Reality |
|---|---|
| OOP means inheritance | Kay left inheritance out of early Smalltalk; Go has none; the core is messaging, hiding, late binding |
| The four pillars are an official definition | Folklore; Cardelli and Wegner's 1985 definition and Kay's 2003 e-mail are the primary sources |
| Private fields plus getters and setters is encapsulation | That is data hiding; encapsulation means the object controls which state changes are allowed |
| Abstraction means abstract classes | Abstraction is a decision about what callers need; abstract classes are one way to write it down |
| Aggregation and composition are synonyms | UML composition means one owner and shared lifetime; UML aggregation has no fixed meaning; GoF use "aggregation" for UML composition |
| Polymorphism means overriding | Subtype, parametric (generics) and ad-hoc (overloading, coercion) are all polymorphism |
| Go is not object-oriented | Go has objects, methods, interfaces and encapsulation; it has no type hierarchy |
| Embedding in Go is inheritance | Promoted methods run on the inner receiver; there is no override through self-calls |
| PHP traits are multiple inheritance | A trait is copied into the class and is not a type; you cannot type-hint a trait |
== tells you if two objects are the same | Value equality, identity equality and language operators are three different things |
| A good model mirrors the real world | GoF: strict real-world modeling reflects today, not tomorrow; model what changes and what the software must answer |
| Every class should be an object with behaviour | DTOs, messages and rows are data structures on purpose |
| Tell-Don't-Ask bans getters | Fowler warns against "GetterEradicators"; query methods are fine |
| The object model can be shared between services | Only data crosses the network; share contracts, not classes |
Cheat sheet
| Topic | Remember |
|---|---|
| Kay's definition | Messaging, protected local state, extreme late binding |
| Abstraction | Separate behaviour from implementation (Liskov); keep the essential, hide the accidental (Brooks) |
| Encapsulation | Only the object's operations change its state; hide decisions likely to change (Parnas) |
| Data hiding | Language access control: Go lowercase, PHP private, private(set), readonly |
| Decomposition | Ask lifetime, sharing, creator, mutator; association vs shared aggregation vs composition |
| Generalization | is-a needs LSP; behaves-like is an interface; code reuse is composition |
| GoF | Program to an interface; favour object composition over class inheritance |
| Fragile base class | Self-calls are an invisible contract; compose and forward instead |
| Polymorphism | Subtype (interfaces), parametric (generics), ad-hoc (overloading, coercion, type switch) |
| Go vs PHP typing | Go structural interfaces; PHP nominal implements; Python duck typing |
| Objects vs data structures | Objects: easy new types; data structures: easy new functions |
| Value vs entity | Value: attributes, immutable; entity: identity, lifecycle |
| Tell-Don't-Ask | Tell the object what to do; keep honest query methods |
| Construction | Valid from the constructor on; named constructors; factories for polymorphic creation |
| Boundaries | DTOs at process boundaries only; explicit, versioned mappers |
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 three properties does Alan Kay's 2003 definition of OOP name, and which familiar "pillar" is missing from it? Good to know
Answer
Answer: Messaging, local retention and protection and hiding of state-process, and extreme late binding. Inheritance is missing; Kay deliberately left it out of early Smalltalk. See Where it comes from.
2 — A class has private fields and a public setter for every one of them. Is it encapsulated? Must-know
Answer
Answer: Its data is hidden, but its information is not: any caller can still put it into any state, and the rules live in the callers. Encapsulation means the object's operations decide which changes are allowed. See Encapsulation.
3 — Name the essential and the accidental parts of an Order in a shop. Important
Answer
Answer: Essential: lines, quantities, prices, one currency, the draft/placed/cancelled rules. Accidental: PostgreSQL tables, JSON field names, Eloquent, HTTP. See Abstraction.
4 — An invoice and its lines: association, shared aggregation or composition? How does that show up in SQL? Must-know
Answer
Answer: Composition: each line has one owner and dies with it. invoice_id NOT NULL REFERENCES invoices(id) ON DELETE CASCADE, often with a primary key local to the invoice. See Decomposition.
5 — Why does (new CountingTagSet)->addMany(['a','b']) report 4 attempts, and why is the composed version immune? Good to know
Answer
Answer: The base class's addMany() calls add() on $this, which is the subclass's overridden add(), so each tag is counted twice. The composed CountingTags calls the inner object through the interface; the inner object's self-calls go to its own add(), not to the wrapper. See Fragile base class.
6 — Classify: Go generics, PHP interface + implements, Go switch v.(type), PHP "5" + 1. Important
Answer
Answer: Parametric; subtype (nominal); ad-hoc by type switch; ad-hoc coercion. See Polymorphism.
7 — What prints, and why: an SMSNotifier that embeds Notifier and defines Channel(), calling the promoted Send()? Good to know
Answer
Answer: [email] ...: the promoted method's receiver is the inner Notifier, whose Channel() returns "email". Go embedding has no override through self-calls. See Traits and embedding.
8 — When should you prefer an enum plus match over an interface with one class per variant? Important
Answer
Answer: When the set of variants is small and closed and you expect to add operations more often than variants: the data-structure side of Martin's trade-off. See Objects vs data structures.
9 — Two Customer objects have the same ID and different e-mails. Equal or not? Two Money objects have the same amount and currency. Equal or not? Must-know
Answer
Answer: The customers are the same entity (identity), possibly at different versions. The money values are equal (value equality) and interchangeable. See Identity.
10 — Why does a well-encapsulated Go entity marshal to {}, and what should you do? Important
Answer
Answer: encoding/json only sees exported fields. Do not export them; map the entity to a DTO such as OrderPlacedV1 at the boundary. See Microservices.
11 — Give two limits of the "nouns become classes, verbs become methods" heuristic. Must-know
Answer
Answer: It produces classes for nouns that are only attributes (quantity, time), and it misses design classes with no real-world counterpart (strategies, states, payment interfaces found by asking what will change). See The modeling exercise.
12 — What may cross a microservice boundary from your object model, and what may not? Must-know
Answer
Answer: Data in a versioned contract (IDs, values, timestamps) may; references, object identity, behaviour and shared classes may not. See Microservices.
Glossary
| Term | Meaning |
|---|---|
| Object | State plus the operations on it, reachable only through requests |
| Class | The specification of a family of similar objects and their shared implementation |
| Message (request) | A named request sent to an object; the receiver chooses the method |
| Interface | The set of requests an object accepts; in code, a named set of method signatures |
| Abstraction | Separating what something does from how it does it |
| Abstract data type (ADT) | A type defined by its operations, with its representation hidden (Liskov and Zilles 1974, CLU) |
| Specification | The description of what an abstraction does, without how |
| Essential complexity | Difficulty inherent in the problem (Brooks) |
| Accidental complexity | Difficulty from today's tools and representations (Brooks) |
| Encapsulation | The representation can be changed only through the abstraction's operations |
| Information hiding | Hiding each design decision likely to change inside one module (Parnas 1972) |
| Data hiding | Language access control on members (private, protected, unexported) |
| Invariant | A condition true for every object of a class whenever no method is running |
| Decomposition | Splitting a whole into parts with defined relationships |
| Association | "Knows a": a link between independent objects |
| Shared aggregation | UML white diamond: grouping without fixed semantics; parts may be shared and outlive the whole |
| Composition (composite aggregation) | UML black diamond: a part in at most one whole, deleted with it |
| Acquaintance | GoF's word for association: an object merely knows another |
| Generalization | Relating a specific type to a more general one |
| Class inheritance | Defining one class's implementation in terms of another's (extends) |
| Interface inheritance (subtyping) | Declaring that an object can be used in place of another |
| is-a / behaves-like | Subtype relation / shared interface without shared code |
| White-box reuse | Reuse by subclassing; internals visible (GoF) |
| Black-box reuse | Reuse by composition through interfaces (GoF) |
| Delegation | Composition where the receiver forwards a request to another object |
| Fragile base class | A safe-looking base-class change breaks subclasses that depend on its self-calls |
| Polymorphism | One piece of code working with values of many types |
| Subtype (inclusion) polymorphism | Different classes answer the same interface; chosen at run time |
| Parametric polymorphism | One body of code for any type that fits a constraint (generics) |
| Ad-hoc polymorphism | Different code per type: overloading, coercion, type switches |
| Overloading | Same name, different functions chosen by argument types |
| Coercion | Automatic conversion of a value to the expected type |
| Nominal typing | Subtyping only by declaration (implements) |
| Structural typing | Subtyping by having the methods (Go interfaces) |
| Duck typing | No type check; call the method and see (Python glossary) |
| Dynamic dispatch / late binding | Choosing the method at run time from the receiver |
| Generics | Type parameters on functions and types (Go 1.18+) |
| Data structure | Exposed data with no behaviour (Martin 2019) |
| DTO (Data Transfer Object) | A data structure that carries data between processes (Fowler) |
| Value object | Equal by attributes, no identity, immutable |
| Entity (reference object) | Equal by identity, with a lifecycle |
| Identity | What makes an object the same one across changes |
| Immutability | No operation changes an object; changes produce a new one |
| Aliasing bug | A change through one reference unexpectedly visible through another |
| Tell-Don't-Ask | Tell an object what to do instead of asking for its data and deciding outside |
| Law of Demeter | Talk only to your immediate collaborators (see the composition chapter) |
| Trait | PHP mechanism to copy methods and properties into classes; not a type |
| Mixin | Code mixed into a class from outside its hierarchy |
| Embedding | Go: a field with a type but no name; its methods are promoted to the outer type |
| Constructor / named constructor | The function that creates a valid object / a static creation method with a meaningful name |
| Factory | An object or function that decides which concrete type to create |
| Readonly class | PHP 8.2: every property is readonly |
| Enum | PHP 8.1 enumerations; a closed set of cases, optionally backed by string or int |
| Property hooks | PHP 8.4 get/set logic on a property; virtual properties have no backing value |
| Asymmetric visibility | PHP 8.4 separate read and write visibility, such as public private(set) |
| Anemic domain model | Objects with data and no behaviour; rules in services (Fowler) |
| God object | One class that knows and does too much |
| Deep hierarchy | Many levels of inheritance whose leaves depend on every ancestor |
| CRC card | Class-Responsibility-Collaborator card, a modeling technique (Beck and Cunningham) |
| Simula / Smalltalk / CLU | The first OO language; Kay's message-based language; Liskov's ADT language |
References
- Alan Kay, e-mails to Stefan Ram on the meaning of "object-oriented programming", 23 and 26 July 2003. purl.org/stefan_ram
- Alan Kay, "The Early History of Smalltalk", HOPL-II, 1993. worrydream.com
- D. L. Parnas, "On the Criteria To Be Used in Decomposing Systems into Modules", Communications of the ACM 15(12), 1972. PDF (TU/e course copy)
- Barbara Liskov, "Data Abstraction and Hierarchy", OOPSLA '87 Addendum, 1987 (cites Liskov and Zilles 1974, Liskov and Guttag 1986, Snyder 1986). PDF
- Barbara Liskov and Jeannette Wing, "A Behavioral Notion of Subtyping", ACM TOPLAS 16(6), 1994. PDF
- Luca Cardelli and Peter Wegner, "On Understanding Types, Data Abstraction, and Polymorphism", Computing Surveys 17(4), 1985. PDF
- Frederick P. Brooks, "No Silver Bullet: Essence and Accident in Software Engineering", 1986. PDF
- Gamma, Helm, Johnson, Vlissides, Design Patterns, Addison-Wesley 1994, chapter 1 "Introduction". Course copy of chapter 1
- Leonid Mikhajlov and Emil Sekerinski, "A Study of the Fragile Base Class Problem" (author's copy). PDF
- OMG, Unified Modeling Language 2.5.1, section 9.5.3 (AggregationKind). PDF
- Martin Fowler: TellDontAsk, AnemicDomainModel, ValueObject, EvansClassification, AggregationAndComposition, Data Transfer Object, LocalDTO
- Robert C. Martin, "Classes vs. Data Structures", The Clean Code Blog, 16 June 2019. blog.cleancoder.com
- Eric Evans, Domain-Driven Design Reference, 2015. PDF
- Go: FAQ, Effective Go, Language Specification, An Introduction To Generics
- PHP: PHP 8.4 release, PHP 8.2 release, PHP 8.1 release, Traits, Enumerations, Properties (readonly), Property hooks, Visibility (asymmetric), Interfaces, Comparing objects
- Python, Glossary: duck-typing
- Martin Fowler, refactoring catalog: Replace Subclass with Delegate
- PHP: Overloading
- Laravel 13: Eloquent: Mutators & Casting (value object casting), Eloquent (Fillable/Unguarded attributes, comparing models), Eloquent relationships, Migrations (cascadeOnDelete), Queries (lockForUpdate), API Resources, Validation, Service Container