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.

Intermediate 4 min readLesson 23 of 24

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-patternSymptomFix
God objectOne class (Manager, Utils, AppService) knows and does everything; thousands of linesSplit by responsibility (SRP); extract classes around cohesive data and behaviour
Spaghetti codeTangled control flow, no structure, global stateExtract functions, introduce modules, add tests first
Big ball of mudA whole system without discernible architectureDraw boundaries incrementally (strangler fig), enforce module dependencies
Golden hammerOne tool for everything ("put it in Kafka", "make it a microservice")Choose tools per problem
Lava flowDead or mysterious code nobody dares deleteTests + version control give you the courage to remove it
Copy-paste programmingThe same logic in many places, slowly divergingExtract a shared function — once you have three real copies
Premature optimisationComplex code for speed nobody measuredProfile first; optimise the actual hot path
Premature abstraction / speculative generalityInterfaces, factories and plugin systems for one implementationYAGNI: abstract when the second use case arrives
Anemic domain modelData-only classes with all logic in "service" classesMove behaviour next to the data it uses (when the domain is rich)
Singleton abuseGlobal state everywhereDependency injection (Singleton)
Distributed monolithMicroservices that must deploy togetherRedraw 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, Money validate 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) {...}

Object-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

  1. Get tests around the code first (characterisation tests capture current behaviour, even if it's odd).
  2. Make small, behaviour-preserving steps: rename, extract method, move method, inline. Run tests after each.
  3. Use your IDE's automated refactorings — they're safer than hand edits.
  4. Separate refactoring commits from behaviour changes, so reviews and bisects stay clear.
  5. 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.