Anti-patterns: when patterns hurt

  • Lesson 32 of 32
  • 10 min
  • Intermediate
  • 11 steps

The patterns in this course also hurt when they arrive before their problem. You will spot four common kinds of excess, swap them for the simple version and know when a layer is worth what it costs.

Types for one greeting
—
Hidden dependencies in place()
—
Order of the steps
—
main.tsGreeterFactoryinterfaceGreeterFactoryDefaultGreeterFactoryDefaultGreeterFactoryGreeterinterfaceMailerinterfaceGreeterDefaultGreeterSmtpMailerDefaultGreeterFakeMailerFakeMailergreet()greet()OrdersOrdersAppContextsingletonAppContextPaymentsPaymentsmain.tsCartCartStockStockEmailEmailgreeter.greet("Ana")4 types for one stringmain.ts: a greeting in two hopsconst factory: GreeterFactory =new DefaultGreeterFactory();const greeter = factory.create();greeter.greet("Ana"); // "Hello, Ana"1 implementation1 implementationalways DefaultGreeterWhat each piece decidesGreeterinterface with 1 implementationGreeterFactoryinterface with 1 implementationDefaultGreeterFactoryalways creates DefaultGreeterDefaultGreeterbuilds the textone functionThe same, with a function+const greet = (name: string) =>+`Hello, ${name}`;+greet("Ana"); // "Hello, Ana"the carry: every time you read it1 piece was enoughThe 4 costs of building just in case (Fowler)buildanalysing, coding and testingdelaywhat you did not ship in timecarrycomplexity in every changerepairfixing what was badly thought outAppContext.get() everywhereplace(): 0 parameters, 4 dependenciesOrders depends on a singletonclass Orders {place() {▸const ctx = AppContext.get();ctx.db.save(ctx.cart);ctx.mailer.send(ctx.user);}}creates each piece onceplace(cart, user)Orders declares what it usesclass Orders {+constructor(private db: Db,+private mailer: Mailer) {}+place(cart: Cart, user: User) {this.db.save(cart);this.mailer.send(user);}}cart.changed againstock.reservedmail.sentThree subscriptions, three files// cart.tsbus.on("mail.sent", refreshCart);// stock.tsbus.on("cart.changed", reserve);// mail.tsbus.on("stock.reserved", sendMail);1. reserve, 2. emailThe order, in one functionfunction checkout(cart: Cart) {+reserve(cart);+sendMail(cart);}2 real implementationskeeps the emails in testsAn interface that pays its way▸interface Mailer { send(to: User): void; }class SmtpMailer implements Mailer { /* SMTP */ }class FakeMailer implements Mailer {sent: User[] = [];send(to: User) { this.sent.push(to); }}Signs that a pattern is too muchinterface with 1 implementationuse the classfactory that always makes the samecall newsingleton everyone fetchespass dependenciesevents that loop backcall in orderthe language already has ituse a functionthe problem firstThe course in one tablea patterna named solutioncreationalwho creates the objectsstructuralhow the pieces fitbehaviouralhow they share the workanti-patterna pattern without its problemfirstthe problem, then the pattern
  • request
  • response
  • event

Step 1 of 11

Problem

Four types to say hello

You open a project and find this to greet a user: a Greeter interface, a GreeterFactory interface, a DefaultGreeter class and a DefaultGreeterFactory class. To get «Hello, Ana», main.ts asks for a factory, the factory creates the greeter and only then does anyone say hello.

That is 4 types and two hops to return a string. Each piece is a pattern you saw in this course, and it is well written. The trouble is not how they are built: it is that none of them solves a problem that exists here.

What changed

  • 4 types for one greeting

Step 2 of 11

Concept

A pattern without its problem

Look at what each piece decides. Greeter has a single implementation, and so does GreeterFactory. The factory always returns a DefaultGreeter: it chooses nothing. Factory exists to decide which class to create; if it is always the same one, it only adds a hop.

This is called an anti-pattern: a solution that keeps coming back, looks good and costs more than it gives. Often it is not a bad pattern but a good pattern applied where its problem is missing.

What changed

  • the same 4 pieces, with what each one decides

Step 3 of 11

Solution

The version that does the same

All of that is replaced by one function: greet(name) returns «Hello, » followed by the name. Same result, 1 piece instead of 4, and whoever reads it understands what it does without opening other files.

If a second real greeting shows up tomorrow, in another language or on another channel, that is when you can pull out a contract. Knowing a pattern for when you need it does not oblige you to use it earlier.

What changed

  • GreeterFactory, Greeter and their classes
  • greet(name)

Step 4 of 11

Trade-off

What building just in case costs

Martin Fowler sums it up as YAGNI («You Aren't Gonna Need It»), a mantra from Extreme Programming. In his 2015 article he separates 4 costs of something built before it is needed: building it, the delay of what you did not ship meanwhile, the carry of its complexity on every change and the repair if it turns out badly thought out.

The 4 greeting pieces charge the carry every time someone reads or changes them. Mind the nuance: Fowler makes clear that YAGNI does not apply to the work of making code easy to change, such as refactoring or writing tests. That is exactly what lets you wait.

Step 5 of 11

Problem

The object everyone fetches

Another classic: an AppContext singleton that holds the database, the cart, the user and the email service. Orders and Payments fetch it with AppContext.get() from any method.

place() takes nothing, but inside it uses 4 dependencies from the context: db, cart, mailer and user. Its signature does not say so, and to test it you have to fill the whole singleton. Miško Hevery put it in the title of a 2008 Google Testing Blog post: «Singletons are Pathological Liars».

What changed

  • AppContext.get() inside every method

Step 6 of 11

Solution

Ask for what you use

Orders receives db and mailer in its constructor, and place() receives the cart and the user. main.ts creates each piece once at startup and hands it to whoever needs it.

The hidden dependencies of place() drop from 4 to 0: they are all in the signature. In a test you pass a fake db and a fake mailer and you are done. It is what you saw in the Singleton and dependency injection lessons, applied to take apart a singleton that grew too much.

What changed

  • AppContext
  • constructor(db, mailer)
  • place(cart, user)

Step 7 of 11

Problem

A chain of events nobody sees whole

Now the shop uses events for everything. The cart emits cart.changed; stock listens, reserves and emits stock.reserved; email listens, sends and emits mail.sent; and the cart listens to mail.sent to refresh itself… and emits cart.changed again.

Each bus.on(...) lives in a different file and looks reasonable on its own. Together they form a loop that never ends, and nobody sees it by reading one file. Observer decouples the sender from the listener; when you need a fixed order of steps, that decoupling hides the order.

What changed

  • 3 subscriptions in 3 files

Step 8 of 11

Solution

If order matters, call in order

checkout(cart) calls reserve(cart) and then sendMail(cart). The order is no longer spread across subscriptions: it reads top to bottom in one function, and if reserve() throws, no email goes out.

Events are still useful when the sender truly does not care who listens, as you saw in the Observer lesson. If a step depends on the previous one, it is a call, not an event.

What changed

  • the chain of events
  • checkout(): reserve, then sendMail

Step 9 of 11

Trade-off

When the layer does pay off

Not every contract with few implementations is too much. Mailer has 2 implementations in use: SmtpMailer in production and FakeMailer in tests, which keeps the emails in a list instead of sending them.

That interface pays for itself: without it, every test would send real emails. So removing patterns is not always good either. Before deleting a layer, look for evidence: a second real implementation, a test that swaps it or a change history that went through it.

What changed

  • Mailer with 2 implementations

Step 10 of 11

Technique

Signs that a pattern is too much

No sign is a rule, but each deserves a question: an interface with 1 implementation and no test that swaps it, a factory that always creates the same class, a singleton that everyone fetches and events that loop back to where they started.

Another sign: writing with classes what your language already has, as you saw in «Patterns your language already has». Remove them in small steps with the tests green, as in «Refactoring toward a pattern», but in the other direction.

What changed

  • the three simple versions, together

Step 11 of 11

Summary

The problem first, then the pattern

An anti-pattern is often a good pattern without its problem: factories that do not choose, interfaces with a single implementation, singletons everyone fetches and events that hide the order. The simple version does the same with fewer pieces, and YAGNI reminds you what it costs to carry the rest.

With this you finish the course. You went through the 23 patterns of the 1994 book and a few more, with their real cases and when not to use them. What you take away is not a catalogue to apply: it is the problem each one solves. When you see it in your code, you know its name; when it is not there, a function is enough.

You will learn

  • Spot a pattern applied where its problem is missing.
  • Name the 4 costs of building just in case, according to YAGNI.
  • Replace a singleton everyone fetches with declared dependencies.
  • Replace a looping chain of events with calls in order.
  • Know when a layer pays off and keep it.