LESSON 10.3
Code smells
Identify symptoms in source code that indicate deeper design problems: Long Methods, Feature Envy, Primitive Obsession, and Shotgun Surgery.
6 min read
A Code Smell is a surface indication that usually corresponds to a deeper design defect in the system. Smells do not prevent code from functioning, but they indicate code that is brittle, error-prone, and difficult to extend.
Common Code Smells & Patterns That Fix Them
| Smell | Description | Target Pattern / Refactoring |
|---|---|---|
| Primitive Obsession | Using primitives (string, number) for domain concepts (Money, Email, ZipCode) | Value Object / Class extraction |
| Feature Envy | A method queries another object's fields repeatedly to do work | Move Method into the target class |
| Long Method / God Class | Methods exceeding 50 lines or classes exceeding 500 lines doing many things | Extract Class / Method, Facade, SRP |
| Shotgun Surgery | A single change requires editing 10 different files | Consolidate logic into one module / Strategy |
| Data Clumps | The same 3 variables (street, city, zip) always passed together | Introduce Parameter Object (Address) |
In code
When to refactor
Follow the Boy Scout Rule: Always leave the code cleaner than you found it. When touching a file to add a feature or fix a bug, take 10 minutes to extract a primitive obsession or eliminate a feature envy. Over time, code quality improves steadily without requiring massive, risky "rewrite everything" projects.
Related patterns
- Primitive Obsession and Value Object: Value Objects are immutable representations with validated domain rules.
- Data Clumps and Parameter Object: Group related parameters into coherent domain objects.
Try it
Ticket Booking LLD
Refactor a ticket booking service plagued with primitive obsession by introducing SeatNumber and Money value objects.