Mediator: a coordinator in the middle

  • Lesson 25 of 32
  • 11 min
  • Intermediate
  • 12 steps

Four parts of a form that all notify each other end up with the same rule copied in several places. You will put a coordinator in the middle, write it in TypeScript and spot the idea in React and in command buses.

Connections between objects
4
emailPanel AControlleremailpasswordPanel BpasswordtermstermssubmitHandlersubmitSignupDialogmediatorAccordionmediatorCommandBusmediatorSignupDialogchanges, tells 3email changes itThe email handleremail.onChange = () => {if (email.value === "")terms.checked = false;submit.enabled =email.value.includes("@") &&pass.value !== "" && terms.checked;};▸// password and terms repeat itanother copy of the ruleand one moreConnections if all call all3 parts34 parts65 parts1010 parts45n × (n − 1) ÷ 2decides who reactsonly says «changed»Before and afterall to all6 connectionswith a mediator4 connectionschanged(w)enabled recomputedSignupDialogchanged(w: Widget) {const f = this.fields;const ok = f.email.value.includes("@");▸if (w === f.email && w.value === "")f.terms.checked = false;▸f.submit.enabled = ok &&f.pass.value !== "" && f.terms.checked;}only knows the mediatorchanged(this)One partclass Field {value = "";▸constructor(private m: Mediator) {}set(v: string) {this.value = v;▸this.m.changed(this); // only reports}}no «@», disabledone more lineInside changed(w)const f = this.fields;const ok = f.email.value.includes("@");+f.pass.enabled = ok; // new ruleif (w === f.email && w.value === "")f.terms.checked = false;f.submit.enabled = ok &&f.pass.value !== "" && f.terms.checked;holds the stateonShow()Accordionconst [active, setActive] = useState(0);return <><Panel isActive={active === 0}onShow={() => setActive(0)} /><Panel isActive={active === 1}onShow={() => setActive(1)} /></>;finds the handler by typeexecute(command)NestJS CQRS// in the controller:this.commandBus.execute(new CreateOrderCommand(userId));// the handler, registered by type:@CommandHandler(CreateOrderCommand)export class CreateOrderHandler {async execute(c: CreateOrderCommand) {…}}knows every partthe centre decidesThree wrong ideas«it is Observer»knows and coordinates«I need a library»one class is enough«all through a bus»sometimes it only hidesgod object?only reportsRules in SignupDialog (example)submit: email, password and termspassword: enabled with «@»terms: unchecked without emailcountry → phone prefixcoupon → final priceplan → business fieldsdirect callenoughWhat a mediator costsone more hopwhen following the codea central classthat can growwith a buswho handles this?the rules live hereonly reportsMediator in one tableproblemparts that all call each othersolutiona mediator they all report togives yourules in one place, reusable partsyou see it inlifting state up, MediatR, CommandBusskip itwith two parts and one rule
  • event
  • request
  • response

Step 1 of 12

Problem

Every part knows the others

A signup form has four parts: email, password, terms (accept the conditions) and the submit button. The button is enabled only when the email has an «@», there is a password and terms is checked. If you clear the email, terms is unchecked.

The direct way: the email handler changes terms and submit itself, and password and terms do the same with the others. In the end every part knows the other three: 6 connections between 4 objects.

What changed

  • email.onChange changes terms and submit

Step 2 of 12

Problem

One rule, three copies

The submit rule is written in the email, password and terms handlers. Now you are asked for passwords of at least 8 characters (an example value): you have to change three places and miss none.

And the web grows fast: if every part knows all the others, n parts have n × (n − 1) ÷ 2 connections. With 4 that is 6; with 10 it would be 45. No part owns the rules, and none can move to another form without dragging the rest along.

What changed

  • the submit rule, in 3 handlers

Step 3 of 12

Concept

A coordinator in the middle

The Mediator idea: you put one object in the middle, SignupDialog, and the parts stop talking to each other. Each one only tells it «I changed», and the mediator decides who else has to react.

Think of an airport control tower: planes do not coordinate among themselves, they talk to the tower. Here the 6 connections become 4, one per part. The Gang of Four book's example is exactly a dialog box coordinating its controls.

What changed

  • SignupDialog, the mediator
  • the 6 direct connections

Step 4 of 12

Technique

The rules, in one place

SignupDialog keeps the four parts in this.fields and has one method, changed(w). Every rule lives there: uncheck terms when the email is cleared and recompute submit.enabled.

It receives the part that changed (w) to know what happened. Asking for 8 password characters is now one line to change, here and nowhere else.

What changed

  • changed(w), with every rule

Step 5 of 12

Technique

Each part only reports

On the other side, a part such as Field stores its value and calls this.m.changed(this). It does not know that terms or submit exist: it only knows an interface, interface Mediator { changed(w: Widget): void }.

That makes it reusable: the same Field works in a login form, with another mediator and other rules. The checkbox and the button work the same way.

What changed

  • Field reports with changed(this)
  • references to the other parts

Step 6 of 12

Solution

A new rule, one line

New request: password stays disabled while the email has no «@». In the old web you would have to pick which handler does it and notify everyone that depends on password.

With the mediator it is one line in `changed`: f.pass.enabled = ok. Field, the checkbox and the button do not change. The rules about how the parts interact leave the parts and gather in one object.

What changed

  • f.pass.enabled = ok
  • Field, unchanged

Step 7 of 12

Concept

You already use it: lifting state up

The React docs explain it with an accordion: two sibling Panels and only one open at a time. Instead of one panel controlling the other, the state moves up to their common parent, Accordion, which passes each child a value (isActive) and a handler (onShow). React calls it lifting state up.

The panels never reference each other: they tell the parent and the parent decides. Calling that a mediator is our reading, not a React term: the parent works as one.

What changed

  • SignupDialog → Accordion
  • changed(w) → onShow

Step 8 of 12

Concept

On the backend: command buses

In NestJS, with its CQRS module, the controller does not call the code that creates the order: it runs commandBus.execute(new CreateOrderCommand(...)). The bus finds the handler registered for that command type and hands it over. For events, EventBus.publish() reaches every subscribed handler.

In .NET, MediatR describes itself as an in-process mediator: Send takes a request to its one handler and Publish takes a notification to several. The controller and the handler do not know each other; the bus sits in the middle. If you plan to use MediatR, check its licence: the project now requires license keys.

What changed

  • SignupDialog → CommandBus
  • changed(w) → execute(command)

Step 9 of 12

Concept

Three wrong ideas

«It is the same as Observer»: Observer notifies listeners it does not know. A mediator knows every part and holds the rules between them. They are often combined: the parts can report to the mediator with events.

«I need a library»: a parent component or a class such as SignupDialog is enough.

«Everything must go through a bus»: if a call always goes to the same place and nobody else reacts, the bus only hides where the code goes.

Step 10 of 12

Trade-off

When the centre knows everything

The pattern's risk sits in the middle. Every new rule lands in changed, and if the form grows (country, coupon, business plan, in this example) the mediator fills up with ifs and knows everything. That has a name: a god object, a class that knows and does too much.

The way out is to split by feature: one mediator per form or section, not one for the whole app. You will see it again in the Anti-patterns lesson.

What changed

  • country, coupon and plan rules
  • SignupDialog grows

Step 11 of 12

Trade-off

When not to use it and what it costs

If there are only two or three parts and one simple interaction (the email enables the button), call directly. A mediator there is one more class to read.

What you pay when you do use it: one more hop when following the code (part → mediator → other part), a central class that can grow without limit and, with a bus, the question «who handles this command?» every time you debug.

What changed

  • the mediator
  • a direct call

Step 12 of 12

Summary

A centre that coordinates

When several parts have to react to each other, do not let them all call each other: put in a mediator that each one reports to and that holds the rules. The parts stay simple and reusable.

You will spot it in the React parent that holds the state and in the MediatR and NestJS buses. The price is a central class you must keep small; with two parts and one rule, the direct call is better.

You will learn

  • See why objects that all call each other form a web that is hard to change.
  • Put a mediator in the middle that each part only reports to.
  • Write a mediator in TypeScript with every rule in one place.
  • Spot the idea in React's «lifting state up» and in the MediatR and NestJS buses.
  • Tell it apart from Observer and know when it is too much.