Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 57 ยท Anti-Patterns and Refactoring

Anti-Patterns and Code Smells

Learn the most common design anti-patterns and code smells: god object, spaghetti code, singleton abuse, anemic model, golden hammer and primitive obsession, with fixes.

A design pattern is a solution that keeps showing up because it works. An anti-pattern is the opposite: a "solution" that keeps showing up and keeps causing trouble. It looks reasonable on the day you write it, then gets more expensive with every change. A code smell is a smaller warning sign in the code, such as a method with fourteen parameters. A smell is not a bug. It is a hint that the design underneath may be in trouble.

Learning the common anti-patterns is as useful as learning the patterns. You will meet them in every code base, and you will write a few yourself. The goal is not to feel bad about them. It is to recognize them early, when fixing them is still cheap. The next lesson, Refactoring to Patterns, shows how to fix them safely.

Seven troublemakers

God object One class knows and does everything.
Spaghetti code Control flow nobody can follow.
Singleton abuse Global state in disguise.
Anemic model Data classes with no behavior.
1 / 2

God object

A god object (also called a blob or a god class) is a class that knows too much and does too much. It often has a vague name such as Manager, Helper, Utils or System. It validates input, talks to the database, formats output, sends email and applies business rules, all in one place.

How to spot it:

  • The file is long, and every feature request touches it.
  • Many unrelated fields sit on one object.
  • Tests need a huge setup, because you cannot create the object without all its dependencies.
  • Two developers editing different features keep causing merge conflicts in the same file.

The cause is almost always a violation of the Single Responsibility Principle. Each small addition ("just one more method here") felt cheap. The cure is to find the separate reasons the class changes and give each its own small class. The first example below does exactly that.

JS Splitting a god object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output is the same, but now a change to the discount rule touches only PriceCalculator, and a test can pass a fake mailer instead of printing.

Spaghetti code

Spaghetti code has tangled control flow: deeply nested if statements, jumps between distant parts of the program, shared mutable variables and no clear structure. You cannot read it from top to bottom, because each part depends on the state left behind by another.

Typical signs are functions of several hundred lines, flags such as isSecondPass that change what code further down does, and callbacks nested six levels deep. The fix is rarely clever. Extract small functions with clear names, replace flags with explicit objects, and flatten nesting with early returns. Patterns such as Strategy and State are specifically good at untangling conditionals.

Singleton abuse

The Singleton pattern guarantees one instance. The anti-pattern is using it as a convenient global variable: any code anywhere calls Config.getInstance() or Database.getInstance(). Dependencies become invisible, because a function's signature does not say that it reads the global database. Tests leak state into each other, and you cannot swap in a fake.

The fix is to keep the single instance if you really need only one, but pass it in instead of reaching for it. This is the idea of dependency injection.

JS Hidden global versus injected dependency

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Anemic domain model

An anemic model has classes that only hold data (fields with getters and setters), while all the rules live in separate "service" classes that reach into the data. It looks like object-oriented code but behaves like procedural code. Nothing stops anyone from putting an object into an invalid state, because the object has no behavior to protect itself.

Compare an Account with a public balance field and a TransferService that subtracts from it, with an Account that has a withdraw() method refusing to go below zero. The second version keeps the rule next to the data it protects. This is the idea of encapsulation from OOP Foundations for Design. Not every service is bad: logic that spans several objects belongs in a service. The smell is when every rule is outside the objects.

Golden hammer

"If all you have is a hammer, everything looks like a nail." The golden hammer is applying one favorite tool, framework or pattern to every problem. A team that has just learned design patterns may wrap everything in factories and observers. A team that loves a database may put queues, caching and configuration into it too.

The cure is to start from the problem. Ask what changes, what must stay stable and what the simplest thing is that works, and only then pick a tool. A function is often better than a class, and a plain if is often better than a Strategy.

Speculative generality

Speculative generality is building flexibility for futures that never arrive: an abstract base class with one subclass, an interface with one implementation "in case we switch", a plugin system with no plugins, parameters nobody passes. It follows from "we might need it someday", and the cost is real: more code to read, test and keep consistent.

The rule of thumb from DRY, KISS, YAGNI and More applies: wait for the second or third real case, then generalize. Refactoring toward flexibility later is usually cheaper than carrying unused flexibility for years.

Primitive obsession

Primitive obsession means using plain strings, numbers and booleans for concepts that deserve their own type: money as a number, a phone number as a string, a status as the magic string "S". The compiler or runtime cannot tell a price from a quantity, and every function has to re-validate its inputs.

A small value object fixes this. It validates once on creation, carries its own behavior and cannot be mixed up with other things.

JS From a bare number to a Money value object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The single mistake of adding dollars to euros now fails loudly in one place instead of silently producing a wrong number somewhere else.

What to do with a smell

A few habits keep anti-patterns under control:

  • Do not rewrite everything at once. Fix one smell at a time, in small steps, with tests passing after each.
  • Fix it where you work. The "boy scout rule" says to leave a file a little cleaner than you found it.
  • Name the problem in review. Saying "this class has three reasons to change" is more useful than "this feels messy".
  • Know when to leave it. Ugly code that never changes and works is cheap. Spend effort where change happens.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class called AppManager has 40 methods covering login, invoices, emails and reports. What is it?

    A class that knows and does everything has many reasons to change. That is the god object anti-pattern, a violation of the Single Responsibility Principle.
  2. 2. What is the main problem with calling Config.getInstance() from deep inside many functions?

    Hidden global access makes a function's real inputs invisible and lets state leak between tests. Passing the dependency in keeps the signature honest.
  3. 3. Which change fixes primitive obsession?

    A value object such as Money validates once, carries behavior and cannot be mixed up with unrelated numbers.
  4. 4. An interface has exactly one implementation and no plan for a second. Which smell may this be?

    Building flexibility for a future that has not arrived adds code to maintain without a benefit. Wait for the real second case.
  5. 5. Which sentence best describes an anemic domain model?

    Data-only objects cannot protect their own invariants, so any code can put them in an invalid state.

Summary

  • An anti-pattern is a common solution that causes more problems than it solves; a code smell is a hint that one may be present.
  • God object: split by reasons to change. Spaghetti code: extract, name, flatten, use Strategy or State.
  • Singleton abuse: inject the dependency instead of reaching for a global.
  • Anemic model: move rules next to the data they protect.
  • Golden hammer and speculative generality: start from the real problem and wait for the second real case.
  • Primitive obsession: replace bare strings and numbers with small value objects.

Next lesson: Refactoring to Patterns.