Anti-Patterns & Code Smells
Recognising bad design — god objects, spaghetti code, golden hammers, premature abstraction, primitive obsession, feature envy and more — with the refactorings that fix them.
An anti-pattern is a common response to a recurring problem that looks reasonable but backfires. A code smell is a surface symptom that often points to a deeper design problem. Knowing them by name helps you spot them in review and explain why something should change.
Design anti-patterns
| Anti-pattern | Symptom | Fix |
|---|---|---|
| God object | One class (Manager, Utils, AppService) knows and does everything; thousands of lines | Split by responsibility (SRP); extract classes around cohesive data and behaviour |
| Spaghetti code | Tangled control flow, no structure, global state | Extract functions, introduce modules, add tests first |
| Big ball of mud | A whole system without discernible architecture | Draw boundaries incrementally (strangler fig), enforce module dependencies |
| Golden hammer | One tool for everything ("put it in Kafka", "make it a microservice") | Choose tools per problem |
| Lava flow | Dead or mysterious code nobody dares delete | Tests + version control give you the courage to remove it |
| Copy-paste programming | The same logic in many places, slowly diverging | Extract a shared function — once you have three real copies |
| Premature optimisation | Complex code for speed nobody measured | Profile first; optimise the actual hot path |
| Premature abstraction / speculative generality | Interfaces, factories and plugin systems for one implementation | YAGNI: abstract when the second use case arrives |
| Anemic domain model | Data-only classes with all logic in "service" classes | Move behaviour next to the data it uses (when the domain is rich) |
| Singleton abuse | Global state everywhere | Dependency injection (Singleton) |
| Distributed monolith | Microservices that must deploy together | Redraw boundaries or merge (Microservices) |
Code smells (from Fowler's Refactoring)
Bloaters
- Long method — more than a screen; does several things. Extract method, name each step.
- Large class — too many fields and methods. Extract class.
- Long parameter list —
create(a, b, c, d, e, f, g). Introduce parameter object or builder. - Primitive obsession — strings and ints for domain concepts (
String email,double money). Replace with value objects:Email,Moneyvalidate themselves and can't be mixed up. - Data clumps — the same group of fields travelling together (
street, city, zip). Make them a class.
Primitive obsession → value objects
// Before: easy to swap arguments, no validation, float money
void transfer(String from, String to, double amount, String currency) {...}
// After
record AccountId(String value) {}
record Money(BigDecimal amount, Currency currency) {
Money {
if (amount.signum() < 0) throw new IllegalArgumentException("negative");
}
Money plus(Money o) { requireSameCurrency(o); return new Money(amount.add(o.amount), currency); }
}
void transfer(AccountId from, AccountId to, Money amount) {...}from dataclasses import dataclass
from decimal import Decimal
@dataclass(frozen=True)
class Money:
amount: Decimal
currency: str
def __post_init__(self):
if self.amount < 0:
raise ValueError("negative money")
def __add__(self, other: "Money") -> "Money":
if other.currency != self.currency:
raise ValueError("currency mismatch")
return Money(self.amount + other.amount, self.currency)
def transfer(source: AccountId, target: AccountId, amount: Money): ...// Branded types: zero runtime cost, compile-time safety
type AccountId = string & { readonly __brand: "AccountId" };
type Cents = number & { readonly __brand: "Cents" };
const accountId = (s: string) => s as AccountId;
const cents = (n: number): Cents => {
if (!Number.isInteger(n) || n < 0) throw new Error("invalid amount");
return n as Cents;
};
function transfer(from: AccountId, to: AccountId, amount: Cents) {}
// transfer(amount, from, to) -> compile errorObject-orientation abusers
- Switch statements on type repeated in several places → polymorphism (Strategy, State).
- Refused bequest — a subclass that doesn't want most of what it inherits → composition instead.
- Temporary field — fields only set in some situations.
Change preventers
- Divergent change — one class changes for many unrelated reasons (violates SRP).
- Shotgun surgery — one change requires edits in many classes (the opposite problem: a concept is scattered). Gather it together.
Couplers
- Feature envy — a method that uses another object's data more than its own. Move it there.
- Inappropriate intimacy — classes digging into each other's internals.
- Message chains —
order.getCustomer().getAddress().getCity().getName()(Law of Demeter violation). Add a method that answers the real question. - Middle man — a class that only delegates. Remove it.
Dispensables
- Comments explaining unclear code — rename and extract instead; keep comments for why.
- Dead code, duplicate code, speculative generality, lazy classes that do too little.
How to refactor safely
- Get tests around the code first (characterisation tests capture current behaviour, even if it's odd).
- Make small, behaviour-preserving steps: rename, extract method, move method, inline. Run tests after each.
- Use your IDE's automated refactorings — they're safer than hand edits.
- Separate refactoring commits from behaviour changes, so reviews and bisects stay clear.
- Follow the boy-scout rule: leave code a bit better than you found it, in the area you're already changing.
Key takeaways
- Anti-patterns look sensible but backfire: god objects, golden hammers, premature abstraction, singleton abuse.
- Name smells precisely: long method, primitive obsession, feature envy, shotgun surgery, message chains.
- Value objects cure primitive obsession; polymorphism cures repeated type switches.
- Refactor in small, tested steps, separate from behaviour changes.
- Smells are prompts for judgement, not absolute rules.