Bitpath

Design Patterns

Each pattern starts from code that hurts and ends at the lightest fix your language allows, often a function rather than a class hierarchy. You learn the handful of ideas underneath (depend on behaviour, compose, pass things in) and when a pattern is more ceremony than help.

  • Intermediate
  • 4 units, 12 lessons, 139 exercises
  • Your language
  • Builds on Clean Code & Refactoring

Unit 01 · 3 lessons

The ideas underneath

See the few ideas that every pattern is built from

  1. > start01Depend on behaviour
  2. 02Reasons to change
  3. BOSSPass it in
Unit prize
  1. 01
    Depend on behaviour

    Ask for what an object can do, not what it is

  2. 02
    Reasons to change

    One job per unit, and new cases as new code

  3. BOSS
    Pass it in

    Hand a class its collaborators instead of letting it build them

Read the unit guide

A design pattern is a named answer to a problem that keeps coming back. Most of them are the same three ideas applied to different problems, so learn the ideas first.

Depend on behaviour, not on a class. Code that calls thing.speak() needs something that can speak, nothing more. In Python and JavaScript that is duck typing; TypeScript writes it down as an interface and Python can with a Protocol. Ask for the smallest behaviour you use and anything can be plugged in, including a fake in a test.

Prefer composition to inheritance. A subclass is tied to the inside of its parent: change how the parent calls its own methods and the child breaks. An object that holds another object and forwards to it depends only on what that object promises.

Give each unit one reason to change. A class that computes, formats and sends has three bosses, and every request from one risks the other two. Split along the reasons, and a new requirement should arrive as new code (a new function in a table, a new class with the same method) rather than as an edit to an if-chain that already works. A subtype has to keep its parent's promises, or code written for the parent breaks without a single error.

Pass collaborators in. A class that builds its own bank client can never be given another one. Take the bank as an argument, build the real one once at startup, and the same class runs in production and in a test without knowing the difference. The classic mistake is the opposite: reaching out for a global, which hides an input.

Unit 02 · 3 lessons

Making objects

Decide in one place which object gets built, and with what

  1. 01Factories
  2. 02Builders and options
  3. BOSSOnly one
Unit prize
  1. 01
    Factories

    One function decides which class to build

  2. 02
    Builders and options

    Named settings, one table of defaults, one final check

  3. BOSS
    Only one

    One shared instance, and what sharing it costs

Read the unit guide

Creating an object looks trivial until the choice of class, or the list of settings, starts to spread through the code. The patterns in this unit put each of those decisions in one place.

A factory is a function that decides which class to build. Callers ask for "a reader for this file" and never name a class, so a new kind is added in the factory and nowhere else. When kinds should be addable from outside, use a registry: a table from name to maker that the factory looks up. Every product must answer to the same methods, or callers are back to asking what they got. When there is one class and no choice, call the constructor.

Long positional argument lists are bugs waiting to happen: Server("db", 80, True, False, 30) does not say which number is the timeout. Name the options (keyword arguments in Python, an options object in JavaScript and TypeScript) and merge them over one table of defaults, caller last. A builder goes one step further for objects assembled over several calls: it collects the settings and checks them once, in build().

A singleton is one shared instance behind an access function. It is also a global variable with better manners. Any function that reaches for it has a hidden input, any function that changes it has a hidden output, and tests start to pass or fail depending on what ran before them.

You can have exactly one instance without making it global: build it once at startup and pass it to whoever needs it. The classic pitfall of this unit is shared mutable state, in any costume: a global settings table, a defaults table handed out without copying, a cache that remembers answers computed under old settings.

Unit 03 · 3 lessons

Putting pieces together

Fit together things that were not designed to fit

  1. 01Adapter and facade
  2. 02Decorator and proxy
  3. BOSSTrees of things
Unit prize
  1. 01
    Adapter and facade

    Make their interface look like yours

  2. 02
    Decorator and proxy

    Add behaviour by wrapping, not by editing

  3. BOSS
    Trees of things

    Treat one thing and a group of things the same way

Read the unit guide

Structural patterns are all the same move: put one object in front of another. What differs is why.

An adapter changes the shape of an interface. Your code calls send(to, text), the new vendor wants push(message), and one small class translates between them. Vendor knowledge lives in that class alone, so swapping the vendor again is one new adapter. Make sure the adapter also translates what comes back: return the vendor's raw answer and callers will start depending on it. A facade is the same idea pointed at a crowd: one simple call in front of several parts that must be used in the right order.

A decorator keeps the interface and adds behaviour around it: log the call, cache the answer, try again on failure. In these languages it is usually a function that takes a function and returns a new one. The wrapped code is not edited. Wrappers stack, and order matters: the outermost one sees every call, an inner one only what gets past the outer. A proxy is a wrapper that decides whether and when the real object is used at all, for example by creating it late.

A composite is a tree in which a single thing and a group of things answer the same question. A file knows its size; a folder asks its children and adds up. Callers never check which one they hold, and a new kind of item only has to answer the same method. An iterator walks such a structure and hands out the items one by one, so that the caller does not need to know how it is nested.

The pitfalls: a wrapper that changes the interface it claims to keep, wrappers stacked in the wrong order, and a tree with a cycle in it, where the recursion never reaches a leaf.

Unit 04 · 3 lessons

Deciding what happens

Choose, announce and undo behaviour without long if-chains

  1. 01Strategy
  2. 02Observer
  3. BOSSAn order's lifecycle
Unit prize
  1. 01
    Strategy

    Pass the algorithm in

  2. 02
    Observer

    Announce what happened to whoever cares

  3. BOSS
    An order's lifecycle

    Explicit states, legal moves, and undo

Read the unit guide

Behavioural patterns are about who decides what happens, and when.

A strategy is an algorithm you can swap. The code that needs it takes it as an argument and only knows how to call it. In these languages a strategy is usually a plain function. A table from a name to a function replaces a chain of ifs on a type code, and lets data pick the algorithm while the program runs. When a strategy needs settings of its own, a function that returns a function carries them.

An observer turns a call around. The source keeps a list of functions and calls whatever is on it; whoever cares subscribes. The source stops naming its listeners, so a new reaction needs no edit to it. The costs are real: the flow is harder to follow, one failing listener can silence the rest unless the emitter guards each call, and a listener that never unsubscribes stays alive and keeps running.

When something has a lifecycle, store one state and write the legal moves down as a table. Combinations of flags that should never exist can then not be stored at all, and the lifecycle can be read in one place. A command is an action turned into a value that knows how to reverse itself. A list of commands is a history, and undo is taking the last one off and running it backwards.

Every pattern in this roadmap is a fix for a particular pain. Where the pain is missing, the pattern is only more code to read: a boolean beats a state machine with two states. Start from the code that hurts, and reach for the lightest thing that stops it hurting.

Learn Design Patterns on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy