Why patterns exist

  • Lesson 1 of 32
  • 9 min
  • Beginner
  • 11 steps

Watch a service that knows everyone become hard to change, and what you gain (and pay) by giving the solution a named shape.

your codeUserServiceUserServicelistenerssubscriberslistenersMailerMailerAuditAuditAnalyticsAnalyticsknows Mailer and AuditUserService · v1class UserService {save(email: string) {this.mailer.send(email);this.audit.log(email);}}UserService must changenew reactionUserService · v1 + Analyticsclass UserService {save(email: string) {this.mailer.send(email);this.audit.log(email);+this.analytics.track(email);}}how do I notify without knowing them?Questions that repeatWho creates this object?creationalHow do two parts fit?structuralHow do they notify each other?behavioralthe three families of the classic catalogueonly announces «saved»Mailer and Audit signed upUserService · Observertype Fn = (email: string) => void;class UserService {fns: Fn[] = [];onSaved(fn: Fn) { this.fns.push(fn); }save(email: string) {for (const fn of this.fns) fn(email);}}unchangedsigns itself upSubscriptionsusers.onSaved((e) => mailer.send(e));users.onSaved((e) => audit.log(e));+users.onSaved((e) => analytics.track(e));UserService does not changesubjectobserverobserverPattern cardnameObserverproblemnotify several when something happenssolutionthe subject notifies whoever signed upconsequencesadd reactions without touching itlike addEventListenerYou already use themaddEventListenerObserversort(compareFn)StrategyExpress middlewarechain of responsibilityWhere it came from1977Alexander1987Beck and Cunningham1994GoF · 23 patternstimeline 1975–2000what happens on save?who is signed up?a direct call is enoughA single reactionsave(email: string) {this.mailer.send(email);}Why patterns exista pattern isa named solution shapeworth it forvocabulary and consequencesit is notcode to copyuse itwhen the problem is already there
  • request
  • event

Step 1 of 11

Problem

A service that knows everyone

When a user is saved, they get an email and the audit log gets an entry. The direct way: UserService.save() calls Mailer and Audit.

It works. But now UserService knows every reaction: who they are, what their methods are called and in which order they run.

What changed

  • UserService
  • Mailer and Audit

Step 2 of 11

Problem

Every new reaction edits the service

Now you are asked to track sign-ups with Analytics. To add it you have to open `UserService` and add another line to save().

With every reaction the service grows, its tests must know more classes, and a bug in any of them breaks saving.

What changed

  • Analytics
  • UserService.save(): one more line

Step 3 of 11

Concept

You are not the first with this problem

«Notify several parts when something happens» shows up in user interfaces, backends and games. So do «who creates this object?» and «how do I make two parts fit?».

Because the questions repeat, good answers do too. The classic pattern catalogue groups them in three families: creational, structural and behavioral.

What changed

  • Reactions on hold
  • Three families of questions

Step 4 of 11

Solution

The service notifies, the others sign up

We turn the relation around: UserService keeps a list of functions and, on save, calls each one without knowing what it does.

This shape has a name: Observer. The one that notifies (the subject) does not know the ones listening (the observers); it only knows someone signed up.

What changed

  • listeners: the subscriber list
  • UserService → Mailer and Audit

Step 5 of 11

Technique

Analytics signs itself up

Same request as in step 2: track with Analytics. Now it is one line outside the service: users.onSaved(...).

UserService stays the same, and so do its tests. Removing a reaction means deleting its subscription.

What changed

  • Analytics, by subscription
  • UserService: unchanged

Step 6 of 11

Concept

A name for a way of solving

A pattern is not code to copy: it is the shape of a solution. It is described with four parts: name, problem, solution and consequences.

The code changes with every project and language; the shape stays. That is why in a review «I would put an Observer here» is enough for the team to get the idea and its costs.

What changed

  • Pattern card

Step 7 of 11

Technique

Patterns you use without naming them

button.addEventListener('click', fn) is Observer: the button announces the click and does not know what the signed-up functions do.

list.sort(compareFn) lets you pass the way to compare (Strategy), and in Express each middleware does its part and passes the request on with next() (chain of responsibility).

What changed

  • Three real cases

Step 8 of 11

Concept

An idea that came from architecture

In 1977 architect Christopher Alexander published A Pattern Language, a language of patterns for designing buildings. In 1987, Kent Beck and Ward Cunningham brought the idea to object-oriented programs in an OOPSLA workshop.

In 1994, Gamma, Helm, Johnson and Vlissides (known as the GoF) published Design Patterns, with 23 patterns split into the three families of step 3.

What changed

  • 1977 · 1987 · 1994

Step 9 of 11

Trade-off

Indirection has a price too

With Observer, reading save() no longer tells you what happens on save: you have to find who signed up, and the order of the reactions depends on the order of the subscriptions.

It is one more piece to understand, test and debug. And the name only helps if whoever reads the code knows it.

What changed

  • save(): the flow is no longer visible in one place

Step 10 of 11

Trade-off

One reaction? Call it directly

If saving only sends an email and nothing suggests more reactions are coming, the direct call is clearer. YAGNI: build for what you need today, not for what you imagine.

And before writing classes, look at your language: in 1996 Peter Norvig showed that 16 of the 23 patterns in the book become simpler or invisible in dynamic languages such as Lisp. Our Observer already uses functions, not classes.

What changed

  • listeners, Audit and Analytics
  • Direct call to Mailer

Step 11 of 11

Summary

What you take away

A pattern is a named solution shape for a problem that keeps coming back: name, problem, solution and consequences. It is not code to copy.

It helps you talk with your team and foresee costs. Use it once the problem has shown up, and prefer what your language already has.

You will learn

  • Why the same design problems show up in many programs
  • What a pattern is: name, problem, solution and consequences
  • Where you already use patterns without naming them
  • Where the idea came from and what the 23-pattern book is
  • When applying a pattern is not worth it