Composing Objects & the Law of Demeter
"'Only talk to your friends' is the motto." — Karl Lieberherr, Law of Demeter: Principle of Least Knowledge, Northeastern University
Summary: Build behaviour by assembling small objects that hold each other (composition), and let each method talk only to its immediate friends (Law of Demeter). The two ideas are one habit: hide structure, so structure can change. Focus: Composition vs inheritance, delegation and forwarding, Go embedding, PHP traits, constructor injection and the composition root, the Law of Demeter stated precisely, message chains, Tell Don't Ask, Hide Delegate vs Middle Man, immutability, pipelines and middleware, and the same law between services, in Go and Laravel. Learning goal: Read a line such as $order->customer->address->city, say which friend list it violates and what it will cost, and fix it with Hide Delegate or Tell Don't Ask without creating a pile of pointless wrapper methods.
This page is the complete reference for how objects are put together and who they may talk to. It covers the sources (Gamma et al. 1994, Lieberherr and Holland 1987-1989, Fowler's bliki), every term practitioners use (delegation, forwarding, embedding, trait, composition root, train wreck, middle man, with-er, functional option), how Go and Laravel express each idea, and what the Law of Demeter means when the "objects" are services owned by different teams. It does not re-teach coupling and cohesion, the SOLID principles or the pattern catalogue; it names them and links.
Page map
| If you are looking for | Go to |
|---|---|
| The whole chapter in a few tables | Everything in one minute |
| Why this chapter exists and what it trades | Why composition and demeter |
| Gamma, Lieberherr, Holland, Fowler, Go, PHP traits: who said what | Where it comes from |
| Has-a vs is-a, delegation, forwarding, Strategy, Decorator | Composition vs inheritance, Delegation, Patterns pointer |
| Go embedding, method promotion, no virtual dispatch | Go embedding |
PHP traits, insteadof, abstract trait methods | PHP traits |
| Constructor injection, DI container, composition root | Object graph assembly |
| The Law of Demeter: friends, one dot, exceptions | LoD precisely, One dot, Exceptions |
| Message chains, Tell Don't Ask, Hide Delegate, Middle Man | Message chain, Tell Don't Ask, Hide Delegate, Middle Man |
| With-ers, functional options, pipelines, middleware | Immutability, Pipelines |
| Orchestration, choreography, reaching through another service | Across services |
| Eloquent chains and Go struct reach-through, before and after | Go, Laravel |
| How to find violations and tell them from false alarms | Mechanics |
| Monolith to distributed systems | In architecture |
| A refactoring kata, wrong beliefs, cheat sheet, self-check | Lab, Misconceptions, Cheat sheet, Self-check |
Everything in one minute
The vocabulary. Every row is unpacked in the concepts section.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Composition | An object is built from other objects it holds | Checkout holds a Notifier | Behaviour is welded to a class tree |
| Inheritance | A class takes everything from a parent class | class SmsNotifier extends Notifier | Fragile base class, deep trees |
| Delegation | "I will ask my helper to do it" | cart.discount.Apply(sum) | Logic duplicated or inherited |
| Forwarding | A wrapper passes the call on unchanged | Logging.Send calls Next.Send | Callers see the inner object |
| Embedding (Go) | Listing a type in a struct without a field name | struct { *log.Logger } | Hand-written forwarding methods |
| Trait (PHP) | A reusable group of methods copied into a class | use HasSlug; | Copy-paste across unrelated classes |
| Constructor injection | Dependencies arrive as constructor arguments | NewCheckout(store, mailer) | Hidden new, untestable code |
| Composition root | The one place where the object graph is built | main(), a service provider | new scattered everywhere |
| Law of Demeter | A method talks only to its friends | order.ShipTo() not order.c.a.city | Callers know your internals |
| Message chain / train wreck | a.b().c().d() | $order->customer->address->city | Every link is a break point |
| Tell, Don't Ask | Tell an object what to do, do not pull its data out | monitor.setValue(3) | Logic leaks into callers |
| Hide Delegate | Add a method that hides the walk | person.manager() | Callers depend on the structure |
| Middle Man | A class that only forwards | 20 one-line wrappers | Indirection with no value |
| With-er | A method that returns a changed copy | money.WithCents(5) | Shared mutable state |
| Functional option | A function that configures a constructor | NewClient(WithTimeout(d)) | Telescoping constructors |
| Pipeline / middleware | Handlers composed into a chain at runtime | Chain(h, Logging, Auth) | Cross-cutting code in every handler |
Who a method may talk to (the friends).
| Friend | Example | Why it is allowed |
|---|---|---|
| The object itself | this.validate() | It is the method's own object |
| The method's parameters | payment.Charge() | The caller chose to hand them over |
| Objects the method creates | x := NewX(); x.Run() | The method owns them |
| The object's direct components | this.store.Save() | The object holds them on purpose |
| Globals/singletons the object can see | config.Default() | Allowed by the original law, discouraged today (hidden dependency) |
| Objects returned by a friend | a.GetB().GetC().Do() | Strangers. Not allowed |
Where each idea lives in your tools.
| Idea | Go | Laravel (PHP 8.4) |
|---|---|---|
| Compose | Struct fields, small interfaces | Constructor property promotion, contracts |
| Reuse without a tree | Embedding, interface embedding | Traits (with care), composition |
| Wiring | main() | Service providers and the container |
| Runtime chain | func(http.Handler) http.Handler | Middleware, Pipeline |
| Hide structure | Methods on the owning type, internal/ | Model methods, accessors, API Resources |
| Immutability | Value receivers, with-ers, options | readonly class, with* methods |
Why composition and demeter
An object graph is a map of who knows whom. Two questions decide whether it survives change: how is a new behaviour added (by editing a class tree, or by plugging in another object?) and how far does one object see (only its neighbours, or the whole map?). Composition answers the first, the Law of Demeter answers the second. Together they keep the number of things a change can break small.
| Choice | You gain | You pay |
|---|---|---|
| Composition over inheritance | Swap behaviour at runtime, test with fakes, no fragile base class | More small types, explicit wiring, forwarding code |
| Inheritance | Free reuse, polymorphism in one step | A tight, compile-time link to the parent's internals |
| Obeying the Law of Demeter | Callers survive structure changes | Extra delegating methods (wider interfaces) |
| Ignoring it for plain data | Short code, no wrappers | Structure leaks into every caller |
Everyday picture. You pay a shop cashier. You hand over your money; you do not let the cashier reach into your wallet, count your notes and pick the ones they like. And you do not ask the cashier to open the till, take out the manager's keys and walk to the safe. Each person deals with the one next to them; what happens behind them is their business. That is "only talk to your friends", and it is also why a shop can change its till without retraining customers.
Three common misunderstandings, up front
- "Composition means never use inheritance." No. The advice is favour composition; inheritance is still right for a true, stable is-a relationship that respects the Liskov Substitution Principle.
- "The Law of Demeter means one dot per line." No. The dot count is a smell detector, not the law.
strings.TrimSpace(s).ToUpper()andUser::query()->where(...)->get()are fine; the law is about whose methods you call. - "Go embedding is inheritance with a different syntax." No. The embedded type never calls back into the outer type. There is no virtual dispatch (Go embedding).
Where it comes from
| Year | Source | What it contributed |
|---|---|---|
| 1987 | Ian Holland, Northeastern University (the Demeter project) | The style rule that became the Law of Demeter, "Law of Good Style" |
| 1988 | Lieberherr, Holland, Riel, "Object-Oriented Programming: An Objective Sense of Style", OOPSLA '88 | First published formal statement, the strong and weak versions |
| 1989 | Lieberherr and Holland, "Assuring Good Style for Object-Oriented Programs", IEEE Software, September 1989, pp. 38-48 | The general formulation (cited from the author's page; the paper itself was not retrievable) |
| 1994 | Gamma, Helm, Johnson, Vlissides, Design Patterns | "Favor object composition over class inheritance" (p. 20, cited via Wikipedia, secondary) |
| 2000 | Hunt and Thomas, The Pragmatic Programmer | Popularised the Law for working programmers (Lieberherr's page: "A 2000 book that describes it well") |
| 2005 | Fowler and Evans, "Fluent Interface" | A deliberate chain of calls on one object |
| 2013 | Fowler, "Tell Don't Ask" | Move behaviour next to the data |
| 2012+ | Go 1 (embedding, interfaces), PHP 5.4 (traits), Laravel container, pipelines | Language and framework forms of composition |
What Lieberherr's page says. "The Law of Demeter (LoD) is a simple style rule for designing object-oriented systems. 'Only talk to your friends' is the motto. The style rule was first proposed at Northeastern University in the fall of 1987 by Ian Holland." (https://www.ccs.neu.edu/home/lieber/LoD.html).
What the 1988 paper says the rule is for. The motivation, in the authors' words: "The motivation behind this Law is to ensure that the software is as modular as possible. Any method written to obey this Law will only know about the immediate structure of the class to which it is attached." And the formal statement: "For all classes C, and for all methods M attached to C, all objects to which M sends a message must be instances of classes associated with the following classes: 1. The argument classes of M (including C). 2. The instance variable classes of C. (Objects created by M, or by functions or methods which M calls, and objects in global variables are considered as arguments of M.)" (OOPSLA '88 paper, https://www2.ccs.neu.edu/research/demeter/papers/law-of-demeter/oopsla88-law-of-demeter.pdf).
The same paper draws the line that most blog posts forget: "The Law prohibits the nesting of generic accessor function calls, which return objects that are not instance variable objects. It allows the nesting of constructor function calls. An accessor function is a function which returns an object which did exist before the function is called. A constructor function returns an object which did not exist before the function is called." That sentence is the root of the builder and value-chain exceptions.
Strong and weak. The paper also defines two readings. The strong law counts only a class's own instance variables as friends; the weak law counts inherited ones too. Its honest cost note: code under the strong law "tends to have extra methods for a given solution. This can render the code less readable in some cases." (same paper). That is the Middle Man problem, noticed in 1988.
What Fowler says about Tell Don't Ask. "Tell-Don't-Ask is a principle that helps people remember that object-orientation is about bundling data with the functions that operate on that data. It reminds us that rather than asking an object for data and acting on that data, we should instead tell an object what to do." (https://martinfowler.com/bliki/TellDontAsk.html, 5 September 2013).
What the Message Chains smell says. "A message chain occurs when a client requests another object, that object requests yet another one, and so on. These chains mean that the client is dependent on navigation along the class structure. Any changes in these relationships require modifying the client." Treatment: Hide Delegate. And the warning: "Overly aggressive delegate hiding can cause code in which it's hard to see where the functionality is actually occurring. Which is another way of saying, avoid the Middle Man smell as well." (https://refactoring.guru/smells/message-chains, a secondary summary of Fowler's catalogue; the catalogue entry itself, https://refactoring.com/catalog/hideDelegate.html, shows manager = aPerson.department.manager becoming manager = aPerson.manager).
What Effective Go says about embedding. "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." And the key difference: "when we embed a type, the methods of that type become methods of the outer type, but when they are invoked the receiver of the method is the inner type, not the outer one." (https://go.dev/doc/effective_go#embedding).
What the PHP manual says about traits. "Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies." (https://www.php.net/manual/en/language.oop5.traits.php).
What the Laravel container docs say. "Dependency injection is a fancy phrase that essentially means this: class dependencies are 'injected' into the class via the constructor or, in some cases, 'setter' methods." (https://laravel.com/docs/13.x/container).
The concepts, one by one
Composition vs inheritance Must-know
In plain words: Inheritance says "a SmsNotifier is a Notifier, and gets all its code". Composition says "a Checkout has a Notifier and asks it to send". With composition you can change the notifier without touching Checkout; with inheritance you change the class you are in.
Common misunderstanding: "Inheritance is for reuse." It is for substitutability: a subtype must be usable wherever the parent is. Reuse of code alone is better served by holding an object.
Definition: Class inheritance defines one class in terms of another at compile time (white-box reuse: the child sees the parent's internals). Object composition assembles behaviour from objects that expose only an interface (black-box reuse), and can be rearranged at runtime. The GoF sentence is "favor object composition over class inheritance" (cited via Wikipedia, which gives p. 20 of the 1994 book).
Adding "log every notification" with inheritance With composition
1 class SmsNotifier extends Notifier class Logging implements Notifier { Next }
2 class LoggingSmsNotifier extends SmsNotifier new Logging(new Sms())
3 class LoggingEmailNotifier extends EmailNotifier new Logging(new Email())
4 class LoggingRetryingSmsNotifier ... new Logging(new Retrying(new Sms()))
-> classes = combinations -> objects = combinations, classes stay smallReal scenarios: notification channels with logging, retry and rate limiting; payment gateways with fraud checks; repositories with caching; HTTP clients with auth, retry, tracing.
| Question | Inheritance | Composition |
|---|---|---|
| Link made when | Compile time | Construction time or later |
| Visibility of the other side | Parent internals (protected) | Public interface only |
| Combining N behaviours | Subclass per combination | Wrap or list N objects |
| Test with a fake | Subclass or mock the class | Pass a fake of the interface |
| Failure mode | Fragile base class, Liskov violations | Boilerplate forwarding, wiring mistakes |
| Good fit | True is-a, stable hierarchy, framework extension points | Almost everything else |
Fix / how to use it. In Go there is no class inheritance at all, so "composition over inheritance" is the only mode; see Go embedding. In Laravel prefer a constructor-injected collaborator to a base class: Laravel itself offers contracts (Illuminate\Contracts\Mail\Mailer) so you can depend on an interface.
Delegation and forwarding Must-know
In plain words: Delegation means the object hands part of its job to a helper it holds. Forwarding means a wrapper passes the same call straight through to the inner object.
Common misunderstanding: "Delegation and forwarding are the same." They look alike. In true delegation the helper can act on behalf of the delegator (it receives the delegator's identity, self). In forwarding the helper keeps its own identity: when it calls this, it means itself. Go embedding and PHP composition are forwarding, which is why there is no virtual dispatch.
Definition: a delegating method has the shape func (c *Cart) Total() int { return c.discount.Apply(c.sum()) }. A forwarding method adds nothing: func (l Logging) Send(to, msg string) error { return l.Next.Send(to, msg) }.
1 caller -> Cart.Total()
2 Cart.Total() -> sum items (Cart's own job)
3 Cart.Total() -> discount.Apply(sum) (delegation to a component: a friend)
4 caller <- 1350Real scenarios: a cart that delegates pricing to a discount policy; a repository that delegates caching to a cache object; a controller that delegates to an action class.
// Delegation, forwarding, Strategy and Decorator as composition patterns.
package main
import (
"fmt"
"strings"
)
// Strategy: the varying rule is a small interface held by the context.
type Discount interface {
Apply(cents int) int
}
type NoDiscount struct{}
func (NoDiscount) Apply(c int) int { return c }
type Percent struct{ P int }
func (p Percent) Apply(c int) int { return c - c*p.P/100 }
type Cart struct {
items []int
discount Discount // a direct component; Cart may talk to it
}
func NewCart(d Discount) *Cart { return &Cart{discount: d} }
func (c *Cart) Add(cents int) { c.items = append(c.items, cents) }
func (c *Cart) Total() int {
sum := 0
for _, i := range c.items {
sum += i
}
return c.discount.Apply(sum) // delegation: Cart asks its collaborator
}
// Decorator: same interface in, same interface out, extra behaviour around.
type Notifier interface {
Send(to, msg string) error
}
type SMS struct{ sent []string }
func (s *SMS) Send(to, msg string) error {
s.sent = append(s.sent, to+": "+msg)
return nil
}
type Logging struct {
Next Notifier // forwarding target
Log func(string)
}
func (l Logging) Send(to, msg string) error {
l.Log("send to " + to)
err := l.Next.Send(to, msg)
if err != nil {
l.Log("failed: " + err.Error())
}
return err
}
type Truncate struct {
Next Notifier
Max int
}
func (t Truncate) Send(to, msg string) error {
if len(msg) > t.Max {
msg = msg[:t.Max]
}
return t.Next.Send(to, msg)
}
func main() {
c := NewCart(Percent{10})
c.Add(1000)
c.Add(500)
fmt.Println(c.Total()) // 1350
var logs []string
sms := &SMS{}
// Behaviour is assembled at runtime, outermost first.
var n Notifier = Logging{Next: Truncate{Next: sms, Max: 10}, Log: func(s string) { logs = append(logs, s) }}
_ = n.Send("+98912", "your order has shipped")
fmt.Println(strings.Join(sms.sent, "|"), len(logs))
}Strategy and Decorator as composition patterns Important
In plain words: Two Gang-of-Four patterns are composition in its plainest form. Strategy is "plug a rule into me". Decorator is "wrap me with extra behaviour and keep my interface".
Common misunderstanding: "Decorator needs an inheritance tree." In the book it used one; in Go and PHP you just implement the same interface and hold the inner object (the Logging and Truncate types in the snippet above).
Definition: Strategy: context holds an interface, the algorithm varies behind it. Decorator: a wrapper implements the interface and forwards, adding behaviour before or after. Full treatment lives in Structural patterns (Decorator, Proxy, Adapter, Facade) and Behavioral patterns (Strategy, Chain of Responsibility); this page only shows that both are composition.
| Pattern | Holds | Same interface as the held object? | Typical use |
|---|---|---|---|
| Strategy | A rule object | No (context has its own API) | Pricing, sorting, retry policy |
| Decorator | The object it wraps | Yes | Logging, caching, metrics |
| Proxy | The real subject | Yes | Lazy load, access control |
| Adapter | The adaptee | No (converts) | Wrapping a vendor SDK |
| Chain of Responsibility | The next handler | Yes | Middleware, pipelines |
Go embedding Must-know
In plain words: Writing a type name inside a struct without a field name makes that type's methods appear on the outer struct. It saves you from writing forwarding methods. It does not make the outer struct a subclass.
Common misunderstanding: "If Dog embeds Animal and overrides Speak, then Animal.Describe will call the dog's Speak." It will not. The promoted method runs with the inner Animal as its receiver, so it only ever sees Animal.Speak.
Definition: the Go specification says a field declared with a type but no explicit field name is an embedded field; its fields and methods are promoted if the selector is legal. Method-set rules: if S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T, and *S also includes those with receiver *T; if S contains *T, both include receivers T and *T (https://go.dev/ref/spec#Struct_types). Effective Go adds the name rules: "a field or method X hides any other item X in a more deeply nested part of the type", and the same name at the same depth is an error if it is used.
d := Dog{Animal{Name: "Rex"}} Java / PHP: class Dog extends Animal
1 d.Speak() -> Dog.Speak -> "Rex barks" same
2 d.Describe() -> Animal.Describe (receiver: d.Animal)
3 -> a.Speak() -> Animal.Speak -> "Rex makes a sound" Java would call Dog.speak via virtual dispatchReal scenarios: bufio.ReadWriter embeds *Reader and *Writer; a struct embeds *log.Logger to get Println; a wrapper embeds an io.Writer and overrides one method (counting bytes); httptest.ResponseRecorder-style wrappers. Embedding an interface and overriding a single method is Go's lightest Decorator.
| Form | Example | What it gives you | Watch out |
|---|---|---|---|
| Embed a struct value | struct { Animal } | Fields and methods promoted | Promoted methods become public API of the outer type |
| Embed a pointer | struct { *log.Logger } | Same, shared instance, can be nil | Nil pointer panics at call time |
| Embed an interface in a struct | struct { io.Writer } | Decorator: override one method, forward the rest | Calling a method on a nil embedded interface panics |
| Embed an interface in an interface | io.ReadWriter | Bigger contract from small ones | Only interfaces embed in interfaces |
Embed sync.Mutex | struct { sync.Mutex } | Lock/Unlock promoted | Exposes locking to every caller; prefer a named unexported field |
| Name clash at same depth | AB{A; B} both with Hello | Ambiguity only when used | Define AB.Hello yourself |
Fix / how to use it. Embed when you really want the promoted method set as your own API. Use a named field (and explicit forwarding) when you want to keep the collaborator private; that also keeps the Law of Demeter intact, because app.Logger.Printf would make callers depend on the embedded type.
// Embedding is composition with promotion. It is not inheritance:
// there is no virtual dispatch from the inner type back to the outer one.
package main
import (
"fmt"
"io"
"os"
"strings"
)
// ---- 1. Method promotion and the receiver rule ----
type Animal struct{ Name string }
func (a Animal) Speak() string { return a.Name + " makes a sound" }
func (a Animal) Describe() string { return "I am " + a.Name + "; " + a.Speak() }
type Dog struct {
Animal // embedded: Speak and Describe are promoted to Dog
}
// Dog "overrides" Speak by shadowing it. Animal.Describe does not know.
func (d Dog) Speak() string { return d.Name + " barks" }
// ---- 2. Interface embedding builds bigger contracts from small ones ----
type ReadCloser interface {
io.Reader
io.Closer
}
// ---- 3. Embedding a collaborator and decorating one method ----
type countingWriter struct {
io.Writer // the wrapped writer; every Write not redefined is forwarded
n int
}
func (c *countingWriter) Write(p []byte) (int, error) {
n, err := c.Writer.Write(p)
c.n += n
return n, err
}
// ---- 4. Name conflicts at the same depth are ambiguous ----
type A struct{}
func (A) Hello() string { return "A" }
type B struct{}
func (B) Hello() string { return "B" }
type AB struct {
A
B
}
// AB.Hello() would not compile: ambiguous selector. Resolve it explicitly.
func (ab AB) Hello() string { return ab.A.Hello() + "+" + ab.B.Hello() }
func main() {
d := Dog{Animal{Name: "Rex"}}
fmt.Println(d.Speak()) // Rex barks
fmt.Println(d.Describe()) // I am Rex; Rex makes a sound <- no virtual dispatch
var rc ReadCloser = io.NopCloser(strings.NewReader("x"))
_ = rc.Close()
cw := &countingWriter{Writer: os.Stdout}
fmt.Fprintln(cw, "hello")
fmt.Println("bytes written:", cw.n)
fmt.Println(AB{}.Hello())
}PHP traits Must-know
In plain words: A trait is a bundle of methods (and properties) that PHP copies into any class that says use TraitName;. It is copy-and-paste done by the language, not an object the class holds.
Common misunderstanding: "Traits are composition." They are horizontal reuse of code, and the result is still one class whose $this is shared with the trait. You cannot swap a trait at runtime, inject a fake of it, or hide its state: its properties become the host's properties. A collaborator object gives you those; a trait does not.
Definition: the manual says a trait cannot be instantiated on its own and reduces "some limitations of single inheritance". Precedence: "members from the current class override Trait methods, which in turn override inherited methods". Conflicts: "If two Traits insert a method with the same name, a fatal error is produced, if the conflict is not explicitly resolved", resolved with insteadof (choose one) and as (alias or change visibility). Abstract trait methods "impose requirements upon the exhibiting class". Traits may declare static members and, since PHP 8.2, constants.
1 class Robot { use Talk, Greet; } -> Fatal error: both define hello()
2 use Talk, Greet { Talk::hello insteadof Greet; Greet::hello as greetHello; }
3 (new Robot)->hello() -> "Talk"
4 (new Robot)->greetHello() -> "Greet"Real scenarios: Eloquent's HasFactory, SoftDeletes, Notifiable; a HasSlug trait shared by unrelated models; a logging helper mixed into jobs.
| Feature | Syntax | Use it for |
|---|---|---|
| Use several traits | use A, B; | Mixing unrelated capabilities |
| Resolve a clash | A::m insteadof B; | Pick the winner |
| Alias or visibility | B::m as protected n; | Keep both or narrow access |
| Abstract requirement | abstract public function slugSource(): string; | The trait declares what the host must provide |
| Trait state | private int $n = 0; | Avoid: hidden state in every host |
| Static members | static function make() | Call through the class, not the trait (deprecated on the trait in 8.1) |
Fix / how to use it. Use a trait for small stateless helpers and framework hooks. When the code has state, rules that change, or needs a test double, extract an interface and inject it, as in the Counter example.
<?php
namespace App\Support;
// 1. Conflict resolution: two traits define the same method name.
trait Talk
{
public function hello(): string
{
return 'Talk';
}
}
trait Greet
{
public function hello(): string
{
return 'Greet';
}
}
class Robot
{
use Talk, Greet {
Talk::hello insteadof Greet; // pick one
Greet::hello as greetHello; // keep the other under an alias
}
}
// 2. An abstract trait method states what the trait needs from its host.
trait HasSlug
{
abstract public function slugSource(): string;
public function slug(): string
{
return strtolower(preg_replace('/[^A-Za-z0-9]+/', '-', $this->slugSource()));
}
}
class Post
{
use HasSlug;
public function __construct(private string $title)
{
}
public function slugSource(): string
{
return $this->title;
}
}
// 3. Why a trait is not composition: it copies code INTO the class.
// The host and the trait share $this, private state and one namespace.
trait Counts
{
private int $n = 0; // becomes a property of every host class
public function hit(): void
{
$this->n++;
}
}
// Composition would be a separate object with its own state and interface:
interface Counter
{
public function hit(): void;
}
final class InMemoryCounter implements Counter
{
private int $n = 0;
public function hit(): void
{
$this->n++;
}
}
final class Page
{
public function __construct(private Counter $counter) // replaceable, fakeable
{
}
public function view(): void
{
$this->counter->hit();
}
}Object graph assembly: constructor injection, container, composition root Must-know
In plain words: Somebody has to create the objects and connect them. Put all of that in one place near the entry point, and let every other class receive what it needs.
Common misunderstanding: "A DI container is dependency injection." Injection is just passing dependencies in. A container is a tool that automates the passing. Calling the container from inside business code (app()->make(...), resolve(...)) is the Service Locator anti-pattern: the dependency is hidden again.
Definition: Constructor injection: required collaborators are constructor parameters. Composition root: the single place (main in Go, service providers and bootstrap/app.php in Laravel) that knows concrete types and builds the graph. Laravel's container does "zero configuration resolution": it autowires a constructor whose parameters are concrete classes; for interfaces you bind ($this->app->bind(Interface::class, Concrete::class)).
1 main() -> store := &memStore{}
2 main() -> mailer := logMailer{}
3 main() -> co := app.NewCheckout(store, mailer, systemClock{})
4 co.Place(ctx, order) -> store.Save -> mailer.Send (app package never says "new")Real scenarios: swapping the real mailer for a log mailer in staging; a clock interface so tests do not sleep; a repository interface so unit tests need no database.
| Technique | Go | Laravel | Comment |
|---|---|---|---|
| Constructor injection | NewCheckout(s, m, c) | __construct(private OrderStore $store) | Default choice |
| Setter / method injection | Rare, optional dependency | $container->call(), controller method type-hints | For optional or per-call values |
| Container | google/wire (compile-time codegen), uber-go/fx (runtime); many Go teams hand-wire in main | Built in: bind, singleton, contextual binding, tagging | Name the product; do not assume one |
| Service locator | Global registry lookup | app(Foo::class) in domain code | Avoid in business classes |
| Poor man's DI | Wire by hand in main | Wire by hand in a provider | Fine up to dozens of types |
Fix / how to use it. Go: interfaces are declared where they are consumed, one or two methods each; main builds leaves first. Laravel: bind contracts in a service provider; type-hint contracts in constructors; use contextual binding when two classes need different implementations.
// Command shop is the composition root: the only place that knows which
// concrete type implements which interface. Everything is built here, once.
package main
import (
"context"
"fmt"
"log"
"time"
"academy/composition-law-of-demeter/root/app"
)
type memStore struct{ rows map[string]app.Order }
func (m *memStore) Save(_ context.Context, o app.Order) error {
m.rows[o.ID] = o
return nil
}
type logMailer struct{ l *log.Logger }
func (m logMailer) Send(_ context.Context, to, subject string) error {
m.l.Printf("mail to=%s subject=%q", to, subject)
return nil
}
type systemClock struct{}
func (systemClock) Now() string { return time.Now().UTC().Format(time.RFC3339) }
func main() {
// 1. leaves first
store := &memStore{rows: map[string]app.Order{}}
mailer := logMailer{l: log.Default()}
// 2. then the objects that use them
checkout := app.NewCheckout(store, mailer, systemClock{})
// 3. then run
err := checkout.Place(context.Background(), app.Order{ID: "42", Cents: 1999, Email: "sara@example.com"})
fmt.Println("placed:", err == nil, len(store.rows))
}<?php
namespace App\Checkout;
use Illuminate\Contracts\Mail\Mailer as MailerContract;
use Illuminate\Support\ServiceProvider;
interface OrderStore
{
public function save(array $order): void;
}
interface Notifier
{
public function send(string $to, string $message): void;
}
final class EloquentOrderStore implements OrderStore
{
public function save(array $order): void
{
\App\Models\Order::query()->create($order);
}
}
// Constructor injection: dependencies are required and visible.
final class Checkout
{
public function __construct(
private readonly OrderStore $store,
private readonly Notifier $notifier,
) {
}
public function place(array $order): void
{
$this->store->save($order);
$this->notifier->send($order['email'], 'Order received');
}
}
// Decorator: same contract, extra behaviour, wrapped around another Notifier.
final class LoggingNotifier implements Notifier
{
public function __construct(
private readonly Notifier $inner,
private readonly \Psr\Log\LoggerInterface $log,
) {
}
public function send(string $to, string $message): void
{
$this->log->info('notify', ['to' => $to]);
$this->inner->send($to, $message); // forwarding
}
}
final class MailNotifier implements Notifier
{
public function __construct(private readonly MailerContract $mailer)
{
}
public function send(string $to, string $message): void
{
$this->mailer->raw($message, fn ($m) => $m->to($to)->subject('Shop'));
}
}
// The service provider is the composition root: the one place that knows
// which concrete class stands behind which contract.
final class CheckoutServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(OrderStore::class, EloquentOrderStore::class);
$this->app->bind(Notifier::class, fn ($app) => new LoggingNotifier(
$app->make(MailNotifier::class),
$app->make(\Psr\Log\LoggerInterface::class),
));
// Checkout itself needs no binding: the container autowires its constructor.
}
}The Law of Demeter, stated precisely Must-know
In plain words: A method may send messages only to a short list of "friends". Anyone else it learns about by asking a friend is a stranger.
Common misunderstanding: "The law is about not using too many dots." It is about types you depend on. A method that calls a.b().c() depends on the types of a, b() and c(); if b changes shape, this method breaks even though it never mentions B by name.
Definition (for functions). A method m of object a may call methods only on: (1) a itself; (2) m's parameters; (3) objects created inside m; (4) a's direct components (fields); (5) globals visible to a (listed in the original; modern style treats them as hidden dependencies and avoids them). This list is the one on Wikipedia, whose wording follows the 1988 paper (arguments, instance variables, created objects and globals counted as arguments).
1 func (a *A) m(p P) {
2 a.helper() // ok: self
3 p.Run() // ok: parameter
4 x := NewX(); x.Do() // ok: created here
5 a.b.Call() // ok: direct component
6 a.b.Get().Call() // NOT ok: Get() returned an object a does not own
7 }Real scenarios: reading a customer's city from an order; finding a manager through a department; a controller that digs through a request's nested arrays; a service that parses another service's JSON three levels deep.
| Version | Friends | Consequence |
|---|---|---|
| Strong law (1988) | Parameters, own (non-inherited) instance variables | Maximum structure hiding, most delegating methods |
| Weak law (1988) | Also inherited instance variables | Slightly wider reach, weaker change isolation |
| Wikipedia / Hunt-Thomas "for functions" | self, parameters, created, components, globals | The rule most teams quote |
| "Only talk to your friends who share your concerns" (Lieberherr, 2004, LoDC) | Friends plus a concern filter | Pointer to aspect-oriented ideas; not needed day to day |
Fix / how to use it. Replace the stranger-walk with a method on the nearest friend (Hide Delegate), or move the behaviour to where the data lives (Tell Don't Ask), or pass the thing you need as a parameter.
The "one dot" heuristic and its misreadings Important
In plain words: "Use one dot" is a quick way to spot a possible violation. It is a smell, not a verdict.
Common misunderstanding: "Any line with two dots breaks the law, and a line with one dot never does." Neither is true. name.trim().toUpperCase() has two dots and talks to strings (values that return new values). order.customer.address has two dots and is a real violation. And a.getB() with one dot already hands out a stranger that the next line may call.
Definition: the heuristic works when each dot is a call that returns an existing object owned by someone else. It misfires on chains that return a new object (builders, value types, streams).
| Expression | Dots | Violation? | Why |
|---|---|---|---|
$order->shipTo() | 1 | No | Direct friend |
$order->customer->address->city | 3 | Yes | Two hops through objects the order owns |
str.trim().toUpperCase() | 2 | No | Each call returns a new value |
User::query()->where()->orderBy()->get() | 3 | No | Fluent builder: one object, same type |
$items->map(...)->filter(...)->sum() | 3 | No | Collection pipeline over values |
cfg.Server.TLS.Cert (plain struct fields) | 3 | Gray area | Data structure, not behaviour (see exceptions) |
$a = $order->customer; $a->address->city | 2 across lines | Yes | A temporary variable does not remove the stranger |
Fix / how to use it. Do not count dots in code review; ask "whose structure am I depending on?". Tools only flag candidates (see Mechanics).
Exceptions: fluent builders, DTOs and value chains Important
In plain words: Some chains are fine because they do not walk through other objects' internals.
Common misunderstanding: "If I follow the law strictly I must wrap every field of every data class." That is the Middle Man trap. The law protects behaviour-bearing objects whose structure can change; it does not forbid reading a plain data record.
Definition: three families are accepted in practice. (1) Fluent interfaces and builders: Fowler and Evans coined "fluent interface" for APIs "designed to be readable and to flow"; every call returns the same builder (or a new one of the same kind), so you are talking to one friend repeatedly. The 1988 paper itself allows "the nesting of constructor function calls" (calls that return new objects). (2) Value chains: immutable values returning new values (money.Add(x).Round(), strings, dates, collections). (3) DTOs and plain data structures: records with public fields and no behaviour (decoded JSON, config structs, API Resources). Their structure is their interface.
1 $q = User::query(); // one builder
2 $q = $q->where('active', true); // returns the builder (same friend)
3 $q = $q->orderBy('name'); // same friend
4 $users = $q->limit(10)->get(); // result is a Collection of models (new objects)
5 $users->first()->profile->bio // <- NOT a builder chain: this is a graph walk| Chain type | Example | Safe because | Danger sign |
|---|---|---|---|
| Fluent builder | Pipeline::send($x)->through([...])->thenReturn() | Always the same object | Builder mutates shared global state |
| Query builder | DB::table('orders')->where(...)->get() | A DSL, one object | Returns models, then you walk them |
| Value chain | money.Add(a).Round() | New values, no shared structure | Hidden I/O inside a getter |
| DTO / config | cfg.Server.Timeout | Data without behaviour | Pass cfg.Server instead of cfg to narrow knowledge |
| Domain object graph | order.customer.address.city | Never | Always a violation |
Fix / how to use it. When a DTO is deep, give the consumer the slice it needs (NewClient(cfg.Server)) so that the consumer does not know the whole shape.
Message chain and train wreck Must-know
In plain words: A line like a.b().c().d() that makes the caller learn the whole path to its answer. Each . is a place that can break, return null or trigger a query.
Common misunderstanding: "It is harmless; it is just one expression." Cost is not in the line. It is in every other line that does the same walk: when the structure changes, you edit them all, and tests must build the whole graph.
Definition: the Message Chains smell (Fowler, in the Couplers group): "a client requests another object, that object requests yet another one, and so on", so the client "is dependent on navigation along the class structure". "Train wreck" is the popular nickname for the same shape; it is a metaphor, not a term from the primary sources read for this page.
1 ShippingLabelController.show($order)
2 -> $order->customer (query 1 if lazy loaded; null if no customer)
3 -> ->address (query 2; null if no address)
4 -> ->city (finally, a string)
5 customers.address_id renamed to address_ref => every caller edited and re-tested-- What the chain does in a list of 50 orders, with lazy loading (the Eloquent default):
select * from orders limit 50; -- 1
select * from customers where id = ? limit 1; -- x 50
select * from addresses where customer_id = ? limit 1; -- x 50
-- 101 queries. With eager loading it is 3: orders, customers where id in (...), addresses where customer_id in (...).Real scenarios: a Blade view that prints the customer's city through three arrows, repeated in six templates; an API serializer with deep nesting; a Go handler with req.Body.User.Profile.Address.City.
| Smell | Symptom | Treatment | Product note |
|---|---|---|---|
| Message chain | a.b().c().d() | Hide Delegate or Move Method | Fowler catalogue |
| Feature envy | Method uses another object's data more than its own | Move Method | See smells chapter |
| N+1 queries from a chain | Chain in a loop with lazy loading | Eager load and hide the walk | Eloquent with(), Model::preventLazyLoading() |
| Null cascade | ?-> everywhere | Null Object, validate at the boundary | PHP ?->, Go nil checks |
Fix / how to use it. See the full before/after in Go and Laravel.
Tell, Don't Ask Must-know
In plain words: Do not take an object's data, decide something and push the result back. Tell the object what you want and let it decide.
Common misunderstanding: "Tell Don't Ask means no getters." Getters are fine for values you display or serialise. The principle targets decisions: if (order.getStatus() == PAID) order.setStatus(SHIPPED) belongs inside order.ship().
Definition: Fowler: "rather than asking an object for data and acting on that data, we should instead tell an object what to do. This encourages to move behavior into an object to go with the data." His example moves the value > limit check from the caller into TellMonitor.setValue. It also lowers the number of friends a caller needs.
Ask Tell
1 if am.getValue() > am.getLimit() tm.setValue(3)
2 am.getAlarm().warn(am.getName() + "...") -> inside: if value > limit: alarm.warn(...)
caller knows 4 getters + alarm type caller knows 1 methodReal scenarios: invoice.markPaid() instead of setting three fields; cart.addItem(item) that enforces limits instead of callers checking; account.withdraw(100) that rejects overdraft.
| Style | Caller does | Object does | Risk |
|---|---|---|---|
| Ask | Reads, decides, writes | Stores data | Rules duplicated in every caller; invariants broken |
| Tell | Sends one command | Decides, enforces invariants | God object if everything moves in; keep SRP |
| Query for display | Reads values | Exposes values | Fine: this is not a decision |
| Command + query split (CQS) | Commands change, queries return | Both kinds exist | Keeps tell and ask honest |
Fix / how to use it. Move the if into the class that owns the data; keep the class small with SRP.
Hide Delegate Important
In plain words: If clients keep walking through your helper to reach something, add a method on you that does the walk.
Common misunderstanding: "Hide Delegate means copying every method of the delegate onto me." Hide only what clients really use, and name it in your language (shipTo(), not getCustomerAddress()).
Definition: refactoring from manager = aPerson.department.manager to manager = aPerson.manager, with Person gaining get manager() { return this.department.manager } (refactoring.com catalog). It is the inverse of Remove Middle Man.
1 before: Controller -> Order -> Customer -> Address (controller imports 3 models)
2 refactor: add Order.shipTo() (body: this.customer.address -> Destination)
3 after: Controller -> Order.shipTo() (controller imports 1 model + 1 value)
4 later: Address gains 'region' -> only Order.shipTo() changes| Move | When | Result |
|---|---|---|
| Hide Delegate | Many callers walk the same path | One place knows the path |
Extract value (Destination) | Callers need a few fields | Callers depend on a small stable type |
| Move Method | The caller does the work with the data | Behaviour sits with the data |
| Pass a parameter | Only one caller needs it | No new method on the owner |
Fix / how to use it. Hide the delegate behind a domain-named method; do not generate one wrapper per field.
Middle Man Important
In plain words: If most of a class's methods only forward to another class, the class is dead weight.
Common misunderstanding: "Strict Law of Demeter means wrapping everything, so a lot of forwarding is correct." The paper itself warned the strong law "tends to have extra methods". Wikipedia puts it plainly: if a wrapper is needed for many calls, the called object "should have been a dependency in the calling class".
Definition: the Middle Man smell: "If most of a method's classes delegate to another class, Remove Middle Man is in order" (refactoring.guru). Exceptions: "A middle man may have been added to avoid interclass dependencies. Some design patterns create middle man on purpose (such as Proxy or Decorator)."
1 class Order { getCity(){return customer.getAddress().getCity();} getZone(){...} getStreet(){...} getName(){...} ... 14 more }
2 callers now use order.getX() for everything -> Order is a facade for Customer
3 fix: give callers the Customer (or a Destination value) they actually need; remove the 14 wrappers| Situation | Hide Delegate | Remove Middle Man |
|---|---|---|
| 1-3 domain-named methods used by many callers | Yes | No |
| 15 pass-through getters | No | Yes |
| Wrapper adds caching, logging, auth | Keep (it is a Decorator/Proxy) | No |
| Wrapper isolates a vendor SDK | Keep (it is an Adapter) | No |
Fix / how to use it. Review the owner class: if more than half of its public methods are one-line forwards to the same field, expose that field's interface instead, or inject the collaborator where it is needed.
Immutability and composition Important
In plain words: Objects that never change after construction can be shared freely. To "change" one, you build a modified copy.
Common misunderstanding: "Immutable means slow." Copying a small value is cheap and removes whole classes of bugs; for large structures, persistent or structural-sharing designs exist. And "immutable" is about the object's state, not about the program having no state.
Definition: a with-er is a method returning a modified copy (money.WithCents(5)). In Go, value receivers copy the struct, so func (m Money) WithCents(c int64) Money { m.cents = c; return m } is safe. Functional options configure a constructor with variadic functions: Rob Pike's 2014 post "Self-referential functions and the design of options" describes the idea, and it is the standard way Go libraries grow options without breaking callers. In PHP 8.4 use readonly class and new static(...) in with-ers.
1 a := NewMoney(1000, "USD")
2 b := a.Add(NewMoney(250, "USD")) // copy; a unchanged
3 a -> 10.00 USD ; b -> 12.50 USD // safe to hand a to any other object| Technique | Go | PHP 8.4 / Laravel | Gain |
|---|---|---|---|
| With-er | Value receiver returning the copy | withCents(): static on a readonly class | Safe sharing |
| Functional option | NewClient(url, WithTimeout(d)) | Named arguments, config objects | Backwards-compatible constructors |
| Builder | strings.Builder, custom builders | Mailable, query builder | Step-by-step construction |
| Value object | Small struct, no pointer | readonly class, Eloquent casts | Equality by value |
| Immutable date | time.Time is a value | CarbonImmutable (Date::use(CarbonImmutable::class)) | No accidental mutation |
Fix / how to use it. Make configuration and domain values immutable; keep mutation inside a few entity types.
// Immutability and composition: with-ers on a value type, functional
// options on a constructor.
package main
import (
"fmt"
"time"
)
// ---- with-ers: every "change" returns a new value ----
type Money struct {
cents int64
currency string
}
func NewMoney(cents int64, cur string) Money { return Money{cents, cur} }
func (m Money) WithCents(c int64) Money { m.cents = c; return m } // m is a copy
func (m Money) Add(o Money) Money { m.cents += o.cents; return m }
func (m Money) String() string {
return fmt.Sprintf("%d.%02d %s", m.cents/100, m.cents%100, m.currency)
}
// ---- functional options (Rob Pike, 2014; Dave Cheney, 2014) ----
type Client struct {
baseURL string
timeout time.Duration
retries int
}
type Option func(*Client)
func WithTimeout(d time.Duration) Option { return func(c *Client) { c.timeout = d } }
func WithRetries(n int) Option { return func(c *Client) { c.retries = n } }
func NewClient(baseURL string, opts ...Option) *Client {
c := &Client{baseURL: baseURL, timeout: 5 * time.Second, retries: 2} // safe defaults
for _, o := range opts {
o(c)
}
return c
}
func main() {
a := NewMoney(1000, "USD")
b := a.Add(NewMoney(250, "USD"))
fmt.Println(a, b) // 10.00 USD 12.50 USD: a is unchanged
c := NewClient("https://api.example.com", WithTimeout(time.Second), WithRetries(5))
fmt.Println(c.baseURL, c.timeout, c.retries)
}<?php
namespace App\Support;
use Illuminate\Support\Collection;
use Illuminate\Support\ServiceProvider;
// Immutability: a readonly value object with "with-ers" that return a copy.
final readonly class Money
{
public function __construct(public int $cents, public string $currency)
{
}
public function withCents(int $cents): static
{
return new static($cents, $this->currency);
}
public function add(self $other): static
{
return $this->withCents($this->cents + $other->cents);
}
}
// Runtime composition with macros: add behaviour to a framework class from the outside.
final class MacroServiceProvider extends ServiceProvider
{
public function boot(): void
{
Collection::macro('toCents', function () {
/** @var Collection $this */
return $this->map(fn ($v) => (int) round($v * 100));
});
}
}
// Fluent interface exception: a builder returns $this by design, so the chain
// talks to ONE object (the query builder) many times, not to many strangers.
// User::query()->where('active', true)->orderBy('name')->limit(10)->get();Composing behaviour at runtime: pipelines and middleware Must-know
In plain words: Build a list of small steps, each passing the request to the next. You change behaviour by changing the list, not the steps.
Common misunderstanding: "Middleware is a framework feature." It is the Decorator/Chain of Responsibility pattern as a function: func(Handler) Handler.
Definition: in Go's net/http, Handler is an interface with ServeHTTP(ResponseWriter, *Request), and HandlerFunc adapts a function to it. A middleware takes a handler and returns a handler. In Laravel, the Pipeline facade sends an input "through a series of invokable classes, closures, or callables", each receiving the input and a $next closure; the docs say it is "very similar to middleware". Class names are built by the container, so stages can take injected dependencies.
1 request -> Logging.start
2 -> RequireKey (header missing: write 403, return; next never called)
3 -> handler (hello)
4 <- RequireKey
5 <- Logging.finish (log method, path, duration)| Concern | Go | Laravel | Short-circuit? |
|---|---|---|---|
| Logging, tracing | Logging(l) middleware | Global/route middleware | No |
| Authentication | RequireKey middleware | auth middleware, EnsureTenantIsActive | Yes (401/403) |
| Rate limit | Middleware with token bucket | throttle middleware | Yes (429) |
| Multi-step workflow | Slice of funcs | Pipeline::send()->through([...]) | Per stage |
| Cross-cutting around a service | Decorator type | Decorator bound in provider | Optional |
Fix / how to use it. Keep stages stateless or inject state; order matters (outermost runs first), so document it.
// A net/http middleware chain: behaviour composed at runtime from small
// func(http.Handler) http.Handler values.
package main
import (
"log"
"net/http"
"net/http/httptest"
"time"
)
type Middleware func(http.Handler) http.Handler
// Chain wraps h so that the first middleware in the list runs outermost.
func Chain(h http.Handler, ms ...Middleware) http.Handler {
for i := len(ms) - 1; i >= 0; i-- {
h = ms[i](h)
}
return h
}
func Logging(l *log.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
l.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start))
})
}
}
func RequireKey(key string) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Api-Key") != key {
http.Error(w, "forbidden", http.StatusForbidden) // short-circuit
return
}
next.ServeHTTP(w, r)
})
}
}
func hello(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("hello")) }
func main() {
h := Chain(http.HandlerFunc(hello), Logging(log.Default()), RequireKey("s3cret"))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
log.Println("status without key:", rec.Code)
}<?php
namespace App\Orders;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Pipeline;
use Symfony\Component\HttpFoundation\Response;
// 1. Pipeline: behaviour composed at runtime from small invokable stages.
final class ApplyCoupon
{
public function __invoke(array $cart, Closure $next): mixed
{
if (($cart['coupon'] ?? null) === 'WELCOME10') {
$cart['total'] = (int) round($cart['total'] * 0.9);
}
return $next($cart);
}
}
final class AddShipping
{
public function __invoke(array $cart, Closure $next): mixed
{
$cart['total'] += 1200;
return $next($cart);
}
}
final class PriceCart
{
public function price(array $cart): array
{
// Class names are resolved through the service container,
// so each stage can take its own constructor dependencies.
return Pipeline::send($cart)
->through([ApplyCoupon::class, AddShipping::class])
->thenReturn();
}
}
// 2. Middleware has the same shape, with a Request in and a Response out.
final class EnsureTenantIsActive
{
public function handle(Request $request, Closure $next): Response
{
if (! $request->user()?->tenant?->isActive()) {
abort(403); // short-circuit: $next is never called
}
return $next($request);
}
}
// bootstrap/app.php registers it:
// ->withMiddleware(fn (Middleware $m) => $m->append(EnsureTenantIsActive::class))Composition across services Important
In plain words: The Law of Demeter applies between services too. A service should not call three other services to assemble a fact, or read another service's tables.
Common misunderstanding: "Microservices are loosely coupled by definition." A service that navigates orders to customers to addresses over HTTP is a distributed train wreck: same coupling, plus latency and partial failure.
Definition: Orchestration has one coordinator that tells others what to do (Tell Don't Ask at system scale). Choreography has services react to published events. The LoD analogue is: consume what a service publishes for you (an event or an API designed for your use), never what it merely stores. Event-carried state transfer puts the needed snapshot in the event so the consumer keeps a local copy (event-driven architecture). API composition and the BFF assemble views for a client in one place instead of in every client.
Before (reach-through) After (publish what is needed)
1 shipping -> orders.GetOrder(id) orders -> publishes OrderPlaced{orderId, shipTo{city,zone}}
2 shipping -> customers.GetCustomer(cid) shipping <- consumes, stores its own row
3 shipping -> addresses.GetAddress(aid) shipping.CityFor(orderId) = local read
4 3 network hops, 3 failure modes 0 network hops at read time; at-least-once => idempotent upsert| Approach | Coupling | Failure mode | Use when |
|---|---|---|---|
| Chain of synchronous calls | High: knows 3 services | Any one down breaks it | Almost never |
| Shared database / read other's tables | Highest | Schema change breaks all | Only inside a modular monolith boundary with owned views |
| Orchestration (one coordinator) | Medium: coordinator knows steps | Coordinator availability | Clear workflow, saga orchestration |
| Choreography (events) | Low: knows events | Hard to trace flow | Independent reactions |
| Event-carried state transfer | Low: knows one event | Stale data until consumed | Read-heavy consumers |
| API composition / BFF | Medium, one place | Aggregator is a dependency | Screens that need many services |
Fix / how to use it. Publish an event with the snapshot consumers need; consume it idempotently (inbox); never share tables (data ownership).
// Package before is a network train wreck: the shipping service walks
// orders -> customers -> addresses with three synchronous calls.
package before
import (
"context"
"fmt"
)
type Orders interface {
GetOrder(ctx context.Context, id string) (customerID string, err error)
}
type Customers interface {
GetCustomer(ctx context.Context, id string) (addressID string, err error)
}
type Addresses interface {
GetAddress(ctx context.Context, id string) (city string, err error)
}
type Shipping struct {
orders Orders
customers Customers
addresses Addresses
}
func New(o Orders, c Customers, a Addresses) *Shipping { return &Shipping{o, c, a} }
// CityFor makes three remote calls. It fails if any of three services is
// down, and breaks when any of three teams renames a field.
func (s *Shipping) CityFor(ctx context.Context, orderID string) (string, error) {
cid, err := s.orders.GetOrder(ctx, orderID)
if err != nil {
return "", fmt.Errorf("orders: %w", err)
}
aid, err := s.customers.GetCustomer(ctx, cid)
if err != nil {
return "", fmt.Errorf("customers: %w", err)
}
return s.addresses.GetAddress(ctx, aid)
}// Package after uses event-carried state transfer: orders publishes what
// shipping needs, and shipping keeps its own small copy.
package after
import (
"context"
"sync"
)
// OrderPlaced is a published contract. It carries the shipping snapshot, so
// consumers do not have to navigate through other services.
type OrderPlaced struct {
OrderID string
ShipTo struct {
City string
Zone string
}
}
type Shipping struct {
mu sync.RWMutex
cities map[string]string // shipping's own read model, keyed by order id
}
func New() *Shipping { return &Shipping{cities: map[string]string{}} }
// Handle is the subscriber side. Make it idempotent: delivery is at-least-once.
func (s *Shipping) Handle(_ context.Context, e OrderPlaced) error {
s.mu.Lock()
defer s.mu.Unlock()
s.cities[e.OrderID] = e.ShipTo.City
return nil
}
// CityFor is a local read: no network, no other service's availability.
func (s *Shipping) CityFor(orderID string) (string, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
c, ok := s.cities[orderID]
return c, ok
}<?php
namespace App\Shipping;
use Illuminate\Support\Facades\Http;
// Before: a network train wreck. Three services, three calls, three failure modes.
final class CityLookup
{
public function cityFor(string $orderId): string
{
$order = Http::get("http://orders/api/orders/{$orderId}")->throw()->json();
$customer = Http::get("http://customers/api/customers/{$order['customer_id']}")->throw()->json();
$address = Http::get("http://addresses/api/addresses/{$customer['address_id']}")->throw()->json();
return $address['city'];
}
}
// After: event-carried state transfer. Orders publishes what shipping needs.
namespace App\Orders\Events;
final readonly class OrderPlaced
{
public function __construct(
public string $orderId,
public string $shipToCity,
public bool $shipToRemote,
) {
}
}
namespace App\Shipping\Listeners;
use App\Orders\Events\OrderPlaced;
use App\Shipping\ShipmentDestination;
final class RememberDestination
{
public function handle(OrderPlaced $event): void
{
// Idempotent upsert into shipping's OWN table; delivery is at-least-once.
ShipmentDestination::updateOrCreate(
['order_id' => $event->orderId],
['city' => $event->shipToCity, 'remote' => $event->shipToRemote],
);
}
}Why tests get easier Must-know
In plain words: If an object receives its collaborators and talks to few of them, a test needs few fakes.
Common misunderstanding: "Tests need a mocking framework." In Go, a three-line struct implementing a one-method interface is the fake. In PHP an anonymous class does it.
Definition: the number of objects a test must construct equals the number of friends the code under test touches (plus what they need). A chain pulls in the whole graph; composition plus the Law of Demeter pulls in exactly the interfaces the code declares.
Test of ShippingFee before after
1 objects built Order+Customer+Address Destination (one struct)
2 fields set to make the rule reachable 6 2
3 test breaks when Address gains a field yes (constructor change) no| Test aid | Go | PHP / Laravel |
|---|---|---|
| Fake of a one-method interface | A struct with the method | Anonymous class implementing the contract |
| Fake clock | Clock interface | Carbon::setTestNow() or a clock interface |
| Fake HTTP | httptest.NewServer | Http::fake() |
| Fake mail | A Mailer fake | Mail::fake() |
| Container swap | Pass a different value in main/test | $this->app->bind(Notifier::class, FakeNotifier::class) in the test |
Fix / how to use it. Write the test first for a collaborator-heavy class: if the setup is long, the design has too many friends.
package app
import (
"context"
"errors"
"testing"
)
type fakeStore struct {
saved []Order
err error
}
func (f *fakeStore) Save(_ context.Context, o Order) error {
if f.err != nil {
return f.err
}
f.saved = append(f.saved, o)
return nil
}
type fakeMailer struct{ subjects []string }
func (f *fakeMailer) Send(_ context.Context, _, subject string) error {
f.subjects = append(f.subjects, subject)
return nil
}
type fixedClock struct{}
func (fixedClock) Now() string { return "T0" }
// No database, no SMTP, no real clock: three tiny fakes are the whole setup.
func TestPlaceSavesAndNotifies(t *testing.T) {
st, ml := &fakeStore{}, &fakeMailer{}
co := NewCheckout(st, ml, fixedClock{})
if err := co.Place(context.Background(), Order{ID: "7", Cents: 100, Email: "a@b.c"}); err != nil {
t.Fatal(err)
}
if len(st.saved) != 1 || st.saved[0].Status != "placed at T0" || len(ml.subjects) != 1 {
t.Fatalf("unexpected state: %+v %+v", st.saved, ml.subjects)
}
}
func TestPlaceDoesNotMailWhenSaveFails(t *testing.T) {
boom := errors.New("db down")
st, ml := &fakeStore{err: boom}, &fakeMailer{}
err := NewCheckout(st, ml, fixedClock{}).Place(context.Background(), Order{ID: "7", Cents: 100})
if !errors.Is(err, boom) || len(ml.subjects) != 0 {
t.Fatalf("err=%v mails=%v", err, ml.subjects)
}
}<?php
namespace Tests\Unit;
use App\Checkout\Checkout;
use App\Checkout\Notifier;
use App\Checkout\OrderStore;
use PHPUnit\Framework\TestCase;
// Plain PHPUnit: no database, no mail, no container, no framework boot.
final class CompositionTest extends TestCase
{
public function test_place_saves_then_notifies(): void
{
$store = new class implements OrderStore {
public array $saved = [];
public function save(array $order): void
{
$this->saved[] = $order;
}
};
$notifier = new class implements Notifier {
public array $sent = [];
public function send(string $to, string $message): void
{
$this->sent[] = [$to, $message];
}
};
(new Checkout($store, $notifier))->place(['id' => 1, 'email' => 'a@b.c']);
$this->assertCount(1, $store->saved);
$this->assertSame([['a@b.c', 'Order received']], $notifier->sent);
}
}Per-language and per-framework view
| Platform | Reuse mechanism | Hides structure by | Wiring | Notes |
|---|---|---|---|---|
| Go | Struct fields, embedding, interface embedding | Unexported fields, internal/ | Hand-wiring in main, google/wire, uber-go/fx | No class inheritance; interfaces satisfied implicitly (Go FAQ: "Why is there no type inheritance?") |
| PHP 8.4 / Laravel 13 | Inheritance, traits, composition | private/protected, readonly, Eloquent accessors | Service container, service providers, contextual binding | Traits copy code; contracts give interfaces |
| Java / Spring | Inheritance, composition, default interface methods | Package-private, modules | Spring IoC container, constructor injection | Closest to the GoF book's setting |
| C# / .NET | Inheritance, extension methods, composition | internal | Microsoft.Extensions.DependencyInjection | Extension methods add behaviour from outside |
| Python | Multiple inheritance, mixins, composition | Naming conventions, properties | Manual or dependency-injector | Duck typing replaces interfaces |
| TypeScript | Classes, structural interfaces | private, module exports | NestJS, tsyringe, manual | Structural typing like Go |
| Rust | Traits and composition, no inheritance | Module privacy | Manual | Composition only |
Mechanics
Finding violations and false alarms Must-know
In plain words: Search for chains, then judge each one by "is this a behaviour-bearing object whose structure may change?".
# PHP / Laravel: three or more arrows on a model chain
grep -rnE '\$[a-z_]+(->[a-zA-Z_]+){3,}' app resources/views | head -50
# Go: three or more selectors on an identifier (data structs will show up too)
grep -rnE '\b[a-z][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){3,}' --include='*.go' . | head -50| Tool | What it checks | Notes |
|---|---|---|
grep / rg with the patterns above | Candidate chains | Many false positives (fluent builders, data) |
| Larastan / PHPStan | Types of each hop, nullable hops | Reports property.nonObject when a hop can be null |
golangci-lint | Style and nilness-type issues | No Demeter linter in the default set |
| Code review | Whose structure is being navigated | The reliable one |
| CK metrics (CBO, RFC) | Coupling between objects, response for a class | Basili et al. 1996 link lower RFC to fewer bugs (via Wikipedia) |
Go: method sets, shadowing and nil Important
| Rule | Example | Consequence |
|---|---|---|
| Promoted methods have the inner receiver | d.Describe() runs Animal.Describe | No virtual dispatch |
| Shallower depth wins | Dog.Speak shadows Animal.Speak | The outer type "overrides" only for outside callers |
| Same depth is ambiguous when used | AB{A; B}.Hello() | Compile error until you define AB.Hello |
Embedded *T can be nil | Job{} then job.Println | Runtime nil dereference |
| Embedded interface satisfied by the outer type | struct{ io.Writer } has Write | Great for decorators; panics if the interface is nil |
| Wrapping loses optional interfaces | A wrapper around http.ResponseWriter hides http.Flusher unless forwarded | Check http.NewResponseController (Go 1.20+) |
PHP: trait precedence and container resolution Important
| Rule | Detail |
|---|---|
| Precedence | Class members override trait methods, trait methods override inherited methods |
| Clash | Fatal error unless insteadof or as resolves it |
| Abstract methods | Enforce the host's contract; since 8.0 the signature must be compatible |
| Properties | Same-name properties must be compatible; avoid trait state |
| Static | Call on the class using the trait, not the trait itself |
| Container | Autowires typed constructor parameters; unresolvable primitives need when(...)->needs(...)->give(...) (contextual binding) |
Go
Before
A function reaches through Order, Customer and Address. It breaks on nil, repeats the walk in two places and forces tests to build all three.
// Package before shows a train wreck: the caller walks the object graph
// Order -> Customer -> Address -> City and knows every type on the way.
package before
import "fmt"
type Address struct {
Street string
City string
Zone string
}
type Customer struct {
Name string
Address *Address
}
type Order struct {
ID int
Customer *Customer
Total int // cents
}
// ShippingFee reaches through three objects. It depends on the shape of
// Order, Customer and Address, and it panics if any link is nil.
func ShippingFee(o *Order) int {
if o.Customer.Address.City == "Tehran" {
return 500
}
if o.Customer.Address.Zone == "remote" {
return 2500
}
return 1200
}
// Label does the same walk again, in a second place.
func Label(o *Order) string {
return fmt.Sprintf("%s, %s %s", o.Customer.Name, o.Customer.Address.Street, o.Customer.Address.City)
}package before
import "testing"
// To test a fee rule we must build the whole graph, three levels deep.
func TestShippingFeeNeedsTheWholeGraph(t *testing.T) {
o := &Order{
ID: 1,
Total: 9000,
Customer: &Customer{
Name: "Sara",
Address: &Address{Street: "Valiasr 1", City: "Tehran", Zone: "urban"},
},
}
if got := ShippingFee(o); got != 500 {
t.Fatalf("fee = %d, want 500", got)
}
}After
Order exposes ShipTo() (Hide Delegate) and ShippingLabel() (Tell Don't Ask). The fee rule takes a small Destination value and is tested with one struct.
// Package after applies Tell, Don't Ask and Hide Delegate: callers talk to
// Order only, and Order talks to its own direct components.
package after
import "fmt"
type address struct {
street string
city string
zone string
}
// Destination is the small, stable view of an address that the rest of the
// system needs. Callers never see the address type.
type Destination struct {
City string
Remote bool
}
type customer struct {
name string
address address
}
type Order struct {
ID int
Total int
customer customer
}
func NewOrder(id, total int, name, street, city, zone string) *Order {
return &Order{ID: id, Total: total, customer: customer{name, address{street, city, zone}}}
}
// ShipTo is the one delegating method (Hide Delegate).
func (o *Order) ShipTo() Destination {
return Destination{City: o.customer.address.city, Remote: o.customer.address.zone == "remote"}
}
// ShippingLabel is "tell": the order renders its own label.
func (o *Order) ShippingLabel() string {
return fmt.Sprintf("%s, %s %s", o.customer.name, o.customer.address.street, o.customer.address.city)
}
// FeeCalculator only knows Destination, a value it receives as a parameter.
type FeeCalculator struct {
Home string
HomeFee int
RemoteFee int
DefaultFee int
}
func (f FeeCalculator) Fee(d Destination) int {
switch {
case d.City == f.Home:
return f.HomeFee
case d.Remote:
return f.RemoteFee
default:
return f.DefaultFee
}
}package after
import "testing"
// The rule is tested with a one-field value; no Order, Customer or Address.
func TestFeeNeedsOnlyADestination(t *testing.T) {
f := FeeCalculator{Home: "Tehran", HomeFee: 500, RemoteFee: 2500, DefaultFee: 1200}
cases := []struct {
d Destination
want int
}{
{Destination{City: "Tehran"}, 500},
{Destination{City: "Yazd", Remote: true}, 2500},
{Destination{City: "Shiraz"}, 1200},
}
for _, c := range cases {
if got := f.Fee(c.d); got != c.want {
t.Errorf("Fee(%+v) = %d, want %d", c.d, got, c.want)
}
}
}The Go angle
- No inheritance, so composition is the language. The Go FAQ explains that Go has no type inheritance; types satisfy interfaces implicitly, so "interfaces can be added after the fact if a new idea comes along or for testing—without annotating the original types" (https://go.dev/doc/faq#inheritance).
- Interfaces belong to the consumer.
app.OrderStorelives in the package that uses it, with one method, so fakes are three lines. - Unexported fields enforce Demeter. In
after,customerandaddressare unexported; callers cannot walk the graph even if they want to. internal/for module-level hiding (see SRP), andmainas the composition root.- Standard library examples:
bufio.ReadWriter(embedding),io.MultiWriter/io.TeeReader(composition of readers and writers),http.Handlerplushttp.HandlerFunc(middleware),http.StripPrefix(a decorator in the standard library). - Functional options (
WithTimeout) and with-ers (Money.WithCents) keep values immutable and constructors stable.
Laravel
Before
A controller reads $order->customer->address->city. In a loop this is also 1 + 2N queries.
<?php
namespace App\Http\Controllers;
use App\Models\Order;
// Before: the caller walks the Eloquent graph and knows every model on the way.
class ShippingLabelController
{
public function show(Order $order): array
{
// Three dots, three models, three places where this can break:
// a null customer, a null address, a renamed column.
$city = $order->customer->address->city;
$fee = $order->customer->address->zone === 'remote'
? 2500
: ($city === 'Tehran' ? 500 : 1200);
// In a loop this is also an N+1 query generator (see the SQL below).
return [
'name' => $order->customer->name,
'line' => $order->customer->address->street.', '.$city,
'fee' => $fee,
];
}
}After
Order::shipTo() hides the walk, the shipping_label accessor tells the order to render itself, and FeeCalculator takes a Destination value. One loadMissing('customer.address') makes the query count explicit.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
// After: Order is the only friend the caller needs. It answers questions
// and performs the work; the graph behind it can change without the caller noticing.
class Order extends Model
{
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class);
}
// Hide Delegate: one method owns the walk through customer -> address.
public function shipTo(): Destination
{
$address = $this->customer->address;
return new Destination(city: $address->city, remote: $address->zone === 'remote');
}
// Tell, Don't Ask: the order renders its own label.
protected function shippingLabel(): Attribute
{
return Attribute::get(fn () => $this->customer->name.', '.$this->customer->address->street.', '.$this->customer->address->city);
}
}
// A small value the rest of the app depends on instead of Customer and Address.
final readonly class Destination
{
public function __construct(public string $city, public bool $remote = false)
{
}
}
namespace App\Shipping;
use App\Models\Destination;
// The fee rule receives a value, not a graph. It is testable with new Destination('Yazd', true).
final class FeeCalculator
{
public function __construct(private string $home = 'Tehran')
{
}
public function fee(Destination $to): int
{
return match (true) {
$to->city === $this->home => 500,
$to->remote => 2500,
default => 1200,
};
}
}
namespace App\Http\Controllers;
use App\Models\Order;
use App\Shipping\FeeCalculator;
class ShippingLabelController
{
public function __construct(private FeeCalculator $fees)
{
}
public function show(Order $order): array
{
// One eager load decides the query count, in one visible place.
$order->loadMissing('customer.address');
return ['line' => $order->shipping_label, 'fee' => $this->fees->fee($order->shipTo())];
}
}The Laravel angle
- Eloquent relationship chains are the classic train wreck.
$order->customer->address->citytriggers lazy loading per hop. Eloquent'sModel::preventLazyLoading(! $this->app->isProduction())(documented under relationships) makes accidental lazy loads throw in development. That is a performance guard, not a design fix; the design fix is the method onOrder. - Relationship shortcuts that are not violations.
hasOneThrough/hasManyThroughdefine a relationship on the model that skips an intermediate table in SQL; callers still talk to one model. Choose it when the intermediate model is a pure join. - API Resources are the DTO layer:
whenLoaded('customer')avoids lazy loads; the resource, not the controller, knows the shape. - Contracts and the container. Laravel's contracts are "a set of interfaces that define the core services provided by the framework". Depend on
Illuminate\Contracts\Mail\Mailerrather than a concrete mailer; facades are convenient but hide the dependency, so prefer constructor injection in domain classes. - Pipeline and middleware give runtime composition; macros (
Collection::macro) add behaviour to a framework class from outside ("macroable"). Declare them in a service provider'sboot. - Traits such as
SoftDeleteshook into Eloquent's lifecycle; do not use traits to share business rules that need test doubles. - Service providers are the composition root.
register()binds,boot()runs after all providers are registered.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Model chain in controllers and views | Hide Delegate + value object | Order::shipTo() returns Destination | One place knows the path | A few more methods |
| Business rule in the caller | Tell Don't Ask | order->markPaid() | Invariants in one place | Risk of a god object; split by actor (SRP) |
| Deep inheritance tree | Replace Inheritance with Delegation | Hold the parent as a field, forward needed methods | Swappable, testable | Forwarding boilerplate |
| Subclass per behaviour combination | Decorator or Strategy | Wrap objects | Combinations at runtime | More objects to wire |
new scattered in business code | Constructor injection + composition root | Pass in interfaces | Fakes in tests | Wiring code grows |
Hidden app() / facade calls | Inject the contract | Constructor parameter | Dependencies visible | Longer constructors (a signal of too many duties) |
| Wrapper class that only forwards | Remove Middle Man | Expose the collaborator or inject it | Less indirection | Callers learn one more type |
| Shared mutable config | Immutable value + with-ers | readonly class, value receivers | Thread-safe, predictable | Copies |
| Cross-cutting code in every handler | Middleware / Pipeline | Compose in one place | Single point of change | Order-dependent |
| Service reaching into another service | Event-carried state, API for the consumer | Publish snapshot | No runtime hop | Data may be stale |
Replace inheritance with delegation (worked move)
1 Before: class CachedRepo extends EloquentRepo { function find($id){ ...cache...; return parent::find($id); } }
2 Step A: introduce interface Repo { find($id) }; EloquentRepo implements Repo
3 Step B: class CachedRepo implements Repo { __construct(Repo $inner, Cache $c) }
4 Step C: CachedRepo::find() { return $c->remember(k, fn() => $inner->find($id)); }
5 Step D: bind Repo to new CachedRepo(new EloquentRepo, $cache) in the service provider
6 Result: tests of CachedRepo use a fake Repo; EloquentRepo no longer carries cache codeChoosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Need to add logging/caching/retry around a service | Decorator via composition | Bind in provider / wire in main | Combinations at runtime |
| Real is-a relationship, stable, Liskov holds | Inheritance is fine | Keep hierarchy shallow | Substitutability |
Framework requires a base class (Model, Controller) | Inherit, but keep logic out of it | Put rules in injected objects | You cannot avoid the extension point |
| Sharing three helper methods between unrelated classes | Trait (PHP) / embedding (Go) | Keep stateless | Cheapest reuse |
| Sharing code that has state or rules that change | Inject a collaborator | Interface at the consumer | Test double, swap |
| Caller needs a nested value | Hide Delegate, return a value object | Destination-style type | Narrow dependency |
| Plain data record read by many | Allow the chain | Pass sub-structs to narrow | Data is its own interface |
| Wrapper has 15 forwarding methods | Remove Middle Man | Inject the collaborator | Less indirection |
| Need many views of related data | API Resource / BFF / read model | Eager load once | One place knows the shape |
| Cross-service data need | Event-carried state | Inbox, idempotent upsert | No chain of calls |
In architecture: from a single process to a distributed system
The same two questions scale: "what do I hold?" and "how far do I see?". At every level the answer is "only the interfaces of my direct collaborators".
Monolith: one process, one database
How it shows up: classes in folders; Eloquent models reaching through each other; controllers that know four models; base classes with logic in them.
Simplest correct usage: one composition root (service providers), constructor injection of contracts, domain methods on models (shipTo()), API Resources as DTOs, preventLazyLoading on in development.
Example (simple): a blog: PostController receives a PostPublisher action; Post::excerpt() instead of $post->body->text->first(200).
Example (production): a shop where Order exposes shipTo(), total(), markPaid(); FeeCalculator, TaxCalculator, Notifier are injected; a Pipeline prices a cart (coupon, shipping, tax) and each stage is replaceable.
Modular monolith and multiple databases
How it shows up: modules own their tables and expose a facade; Demeter is the rule between modules. A module's internal models are strangers to every other module.
-- PostgreSQL: another module sees a view, not tables (the view is the published contract).
CREATE SCHEMA shipping;
CREATE VIEW shipping.order_destinations AS
SELECT o.id AS order_id, a.city, (a.zone = 'remote') AS remote
FROM orders.orders o
JOIN customers.addresses a ON a.customer_id = o.customer_id;
GRANT SELECT ON shipping.order_destinations TO shipping_app;
-- shipping_app never reads orders.* or customers.*; if the join changes, only the view changes.Rules: other modules call Orders::shipTo($id) or read the view; architecture tests (Deptrac, PHPArkitect for PHP; go list -deps or internal/ for Go) fail the build when one module imports another's internals; each module has its own service provider as its composition root.
Microservices: LoD with a network boundary
What survives: composition (each service is a component with an interface) and Demeter (talk to your direct neighbours' contracts). What breaks: if a service reaches through another's data model, a field rename is now a multi-team release.
Checkout flow: "show delivery city on the order page"
1 Wrong: web -> orders -> customers -> addresses (3 hops, 3 teams, 3 timeouts)
2 Better: orders publishes OrderPlaced{shipTo.city}; shipping and web read their own copies
3 Or: BFF calls orders.GetOrderView(id) which returns the assembled view designed for that pageExample: orchestration (Tell Don't Ask) with a saga orchestrator telling payment and stock services what to do; versus choreography where each reacts to OrderPlaced. Both keep any service from navigating another's storage. Publishing reliably needs an outbox.
| Pattern | LoD reading |
|---|---|
| API Gateway / BFF | The one place that composes many services for a client (gateway chapter) |
| Anti-Corruption Layer | A Hide Delegate for a foreign model |
| Event-carried state | Publisher decides what friends may know |
| Shared database | Everyone is a friend of every table: the worst violation |
Distributed data: replicas, caches and shared schemas
Where the law breaks: a cache that stores serialized object graphs makes every reader depend on the graph shape; a read replica queried with arbitrary joins couples every team to the schema; an event that contains a whole entity ($order->toArray()) publishes internals.
Countermeasures: cache small, purpose-built values (shipping:city:{orderId}), version event schemas (message design), expose read models instead of replicas, never serialize ORM models into events.
Scaling path: 1×, 10×, 100×
| Scale | Structure | Composition / Demeter practice |
|---|---|---|
| 1× (one team, one app) | Folders by feature | Constructor injection, domain methods on models, no logic in base classes |
| 10× (several teams, one repo) | Modular monolith | Module facades, views as contracts, per-module providers, architecture tests |
| 100× (many teams, many services) | Services per capability | Published events and APIs designed for consumers, BFF, no shared tables, contract tests |
Lab
You will reproduce a train wreck, measure its cost, and fix it. Everything runs offline.
Setup.
cd docs/snippets/design/composition-law-of-demeter/go
gofmt -l . && go vet ./... && go test ./... # everything compiles, vet is cleanStep 1: count what a test must build.
grep -c '&Customer\|&Address' chain/before/order_test.go chain/after/order_test.go
# chain/before/order_test.go: 2 (Customer and Address are constructed)
# chain/after/order_test.go: 0Step 2: prove the walk is fragile. In chain/before/order.go, rename Address.City to Town. Expected: go build ./chain/before fails in two places (ShippingFee and Label). Now do the same in chain/after/order.go (field city to town): only ShipTo and ShippingLabel inside the type change; no caller edits.
Step 3: prove embedding is not inheritance.
go run ./embedding
# Rex barks
# I am Rex; Rex makes a sound <- Describe did not call Dog.SpeakStep 4: swap a collaborator in a test. Open root/app/service_test.go; note there is no database and no SMTP. Add a failing store (err: boom) and check that no mail is sent (already in the second test).
Step 5: build a middleware chain.
go test ./middleware -run TestChainOrderAndShortCircuit -v
# --- PASS: TestChainOrderAndShortCircuitStep 6 (Laravel, optional). Put ChainBefore.php in a scratch app with two seeded relations and run DB::enableQueryLog() for 50 orders: expect 101 queries. Apply ChainAfter.php and Order::with('customer.address'): expect 3.
| Metric | Before | After |
|---|---|---|
| Types a fee test builds | 3 (Order, Customer, Address) | 1 (Destination) |
Places edited when City is renamed | 2 or more callers | 1 type |
| Queries for 50 orders (Eloquent) | 101 | 3 |
| Nil panics possible in caller | 2 (customer, address) | 0 (inside the owner) |
Common misconceptions
| Belief | Reality |
|---|---|
| "Composition replaces inheritance everywhere" | Favour it; use inheritance for true is-a that respects LSP |
| "Go embedding is inheritance" | Promoted methods keep the inner receiver; there is no virtual dispatch |
| "Traits are composition" | Traits copy code into the class and share its $this; they cannot be swapped or faked |
| "One dot per line is the Law of Demeter" | The law is about whose methods you call; the dot count only flags candidates |
| "Fluent builders violate the law" | A builder returns itself; you talk to one friend. The 1988 paper allows chains of constructor calls |
| "Reading a DTO's fields violates the law" | Plain data records are their own interface; narrow what you pass instead |
| "Follow the law by adding a wrapper for every field" | That creates a Middle Man; hide only what callers really use |
| "A DI container is dependency injection" | Injection is passing arguments; the container only automates it |
"app() inside a class is fine, it is just injection" | That is a service locator; the dependency is hidden |
| "Eager loading fixes the Demeter violation" | It fixes queries; the chain and its coupling remain |
| "Microservices are loosely coupled by default" | A service that walks other services' data is a distributed train wreck |
| "Immutable objects are slow" | Small value copies are cheap and prevent shared-state bugs |
Cheat sheet
| Topic | What to remember |
|---|---|
| Composition | Has-a, via interface, assembled at construction; favour it |
| Inheritance | Only for stable is-a that is substitutable |
| Delegation | Ask a held helper to do part of the job |
| Forwarding | Pass-through wrapper; the inner this stays inner |
| Go embedding | Promotion, inner receiver, no virtual dispatch |
| Interface embedding | Build bigger contracts from one-method ones |
| PHP traits | Code copy; insteadof / as; abstract methods for needs; avoid state |
| Constructor injection | Required collaborators as parameters |
| Composition root | One place builds the graph (main, service provider) |
| Friends | self, parameters, created objects, direct components (globals discouraged) |
| One dot | A smell detector, not the rule |
| Exceptions | Fluent builders, value chains, plain data |
| Tell Don't Ask | Move decisions to the data's owner |
| Hide Delegate | Domain-named method that hides the walk |
| Middle Man | If most methods only forward, remove it |
| With-ers / options | Immutable copies; functional options for constructors |
| Pipeline / middleware | func(Handler) Handler, $next($input), order matters |
| Across services | Consume contracts and events, never another service's tables |
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 — Why does Dog.Describe() in Go print "Rex makes a sound" even though Dog defines Speak? Important
Answer
Answer: The promoted method runs with the inner Animal as receiver, so Animal.Speak is called. Embedding forwards; it does not dispatch virtually. See Go embedding.
2 — Name the friends of a method under the Law of Demeter. Must-know
Answer
Answer: The object itself, the method's parameters, objects created in the method, the object's direct components, and (in the original) globals. See LoD precisely.
3 — Is $users->map(...)->filter(...)->sum() a violation? Important
Answer
Answer: No. It is a collection pipeline over values; each call returns a new collection of the same kind. See Exceptions.
4 — Why are PHP traits not composition? Important
Answer
Answer: They copy methods and state into the host class; they share $this, cannot be swapped at runtime or replaced with a fake. See PHP traits.
5 — What is the composition root and where is it in Laravel? Important
Answer
Answer: The single place that builds the object graph. In Laravel: service providers and bootstrap/app.php; in Go: main. See Object graph assembly.
6 — When is Hide Delegate a mistake? Good to know
Answer
Answer: When it produces many pass-through methods; that is a Middle Man. Hide only what callers use, with domain names. See Middle Man.
7 — How does Tell Don't Ask relate to the Law of Demeter? Must-know
Answer
Answer: Telling the owner what to do removes the need to fetch its parts, so the caller has fewer friends. See Tell Don't Ask.
8 — Does preventLazyLoading fix a Demeter violation? Important
Answer
Answer: No. It makes accidental lazy loading fail loudly; the chain and its coupling remain. Add a method on the owning model. See Laravel angle.
9 — What is the service-level version of a message chain? Important
Answer
Answer: A service calling several services in sequence to assemble a fact, or reading another service's tables. Fix with event-carried state or an API designed for the consumer. See Across services.
10 — Why do tests get easier with composition? Must-know
Answer
Answer: The test builds only the declared interfaces (small fakes), not the whole graph. See Why tests get easier.
Glossary
| Term | Meaning |
|---|---|
| Composition | Building behaviour from objects an object holds |
| Inheritance | Defining a class in terms of a parent class |
| Is-a / Has-a | Subtype relation vs holding relation |
| Delegation | Handing part of the work to a held helper |
| Forwarding | A wrapper passing a call unchanged to the inner object |
| Virtual dispatch | Choosing the method by the runtime type of the receiver |
| Fragile base class | A parent change that breaks subclasses |
| Embedding (Go) | A field with a type and no name; methods are promoted |
| Method promotion | Inner type's methods appear on the outer type |
| Interface embedding | An interface listing other interfaces |
| Trait (PHP) | Group of methods copied into classes with use |
insteadof / as | Trait conflict resolution and alias operators |
| Abstract trait method | A method the host class must implement |
| Constructor injection | Passing dependencies as constructor arguments |
| Service locator | Fetching dependencies from a global registry inside the class |
| DI container | A tool that builds objects and injects their dependencies |
| Composition root | The place where the object graph is assembled |
| Law of Demeter | A method talks only to its friends |
| Friend | Self, parameter, created object, direct component |
| Stranger | An object obtained from a friend's return value |
| Message chain / train wreck | a.b().c().d() navigation |
| Tell, Don't Ask | Command objects instead of pulling their data |
| Hide Delegate | Refactoring that adds a method hiding a walk |
| Middle Man | Class that mostly forwards |
| Fluent interface | API designed to read as a chain on one object |
| DTO | Data transfer object with no behaviour |
| With-er | Method returning a modified copy |
| Functional option | Function that configures a constructor |
| Pipeline / middleware | Chain of handlers composed at runtime |
| Orchestration / choreography | Central coordinator vs events between services |
| Event-carried state transfer | Event contains the data consumers need |
| Anti-Corruption Layer | Adapter that shields a model from a foreign one |
References
- Karl J. Lieberherr, Ian M. Holland, Arthur J. Riel, "Object-Oriented Programming: An Objective Sense of Style", OOPSLA '88 Proceedings. PDF
- Karl J. Lieberherr, Ian M. Holland, "Assuring Good Style for Object-Oriented Programs", IEEE Software, September 1989, pp. 38-48 (cited from the author's page; not retrieved). Law of Demeter page
- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Design Patterns (1994), p. 20, "favor object composition over class inheritance" (cited via Wikipedia: Composition over inheritance, secondary)
- Wikipedia, Law of Demeter (secondary source for the "for functions" list and the "one dot" wording)
- Martin Fowler, Tell Don't Ask, 5 September 2013
- Martin Fowler, Fluent Interface, 20 December 2005
- Refactoring catalog: Hide Delegate, Remove Middle Man; refactoring.guru: Message Chains, Middle Man
- Go: Effective Go: Embedding, Go specification: Struct types, Go FAQ: inheritance, net/http Handler
- Rob Pike, Self-referential functions and the design of options, 24 January 2014
- PHP manual, Traits
- Laravel 13: Service Container, Contracts, Helpers: Pipeline, Middleware, Collections: Extending, Eloquent relationships
- Siblings: Design quality principles, Code smells and refactoring, Structural patterns, Behavioral patterns, SRP, OCP, LSP, DIP