An anti-pattern is a common answer to a recurring problem that looks reasonable at first and then costs more than it saves. A code smell is the visible symptom: a class that keeps growing, a switch that appears in five files, a string that means ten different things. This lesson walks through the smells you will meet most often (God Object, spaghetti code, Primitive Obsession, Shotgun Surgery and friends), shows what each one costs when the next change request arrives, and names the refactoring and the pattern from this track that cures it.
Think of it like
A smell in the fridge
When the fridge smells, you do not know yet what is wrong. It might be the milk, or it might be a strong cheese that is supposed to smell. The smell tells you where to look, not what to throw away. Code smells work the same way: a 600-line class or a long switch is a reason to open the code and check, and sometimes the honest answer is that it is fine. When something really has gone off, you clean it in small steps, one shelf at a time, and the fridge keeps working while you do.
Smells, anti-patterns and refactoring
The vocabulary comes from two books. Refactoring by Martin Fowler (1999, second edition 2018) has a chapter, written with Kent Beck, called "Bad Smells in Code" that names more than twenty smells and the refactorings that remove them. AntiPatterns by Brown, Malveau, McCormick and Mowbray (1998) catalogs larger failures, from the Blob (the God Object) and Spaghetti Code to Lava Flow and the Golden Hammer.
- Code smell
- A surface sign in the code that often, but not always, points to a deeper design problem. Smells are quick to spot: size, repetition, long parameter lists, the same
switchin several places. - Anti-pattern
- A recurring solution that seems sensible and has predictable bad consequences, together with a known better alternative. A smell is what you see; an anti-pattern is the design that produced it.
- Refactoring
- A change to the structure of code that does not change what it does, made in small steps and checked by tests after each one. See Refactoring Toward Patterns.
- Technical debt
- The extra cost of every future change caused by a shortcut taken now. Smells are where the interest is paid.
What the visualizer shows
The visualizer at the top of the page runs three small programs, picked with the God Object / Primitives / Shotgun switch. Each one has a Before version (the smell) and a cured version (With Extract Class, With Value Object or With Polymorphism), and both produce the same results. Each one also has a change request button. Press it and the class diagram puts a badge on every class the change touched, while the Change request panel beside the code counts them for both versions.
- Class diagram: in Before, look at how much sits in one box (God Object) or how the same method shape repeats across boxes (Primitives, Shotgun). In After, the same work is spread over small classes with arrows between them.
- Objects at runtime: in the God Object Before, every message loops from
ordersback toorders; after the cure, messages travel betweencheckout,cart,paymentsandmailer. - Sequence of calls: in the Shotgun Before, the client talks to three services that never talk to anything else, because each one decides on its own. After, each service asks the plan object.
| Change request | Before (the smell) | After (the cure) |
|---|---|---|
| God Object: send this customer's receipt by SMS | 1 class edited (OrderManager), 8 lines | 0 classes edited, 1 new class (SmsNotifier) |
| Primitive Obsession: trim spaces around emails | 3 classes edited (Signup, Newsletter, Invites), 9 lines | 1 class edited (Email), 3 lines |
| Shotgun Surgery: add a Team plan | 3 classes edited (Billing, Limits, Support), 3 lines | 1 class edited (the factory in Plan), 2 lines, and 1 new class (TeamPlan) |
God Object
A God Object (Fowler calls it Large Class, the AntiPatterns book calls it the Blob) is one class that knows and does too much. It usually starts as a sensible OrderManager and grows one convenient method at a time, because adding a method to the class that already has all the data is always the easiest edit.
class OrderManager {
private items: number[] = [];
private paid: string[] = []; // payment data
private outbox: string[] = []; // notification data
add(price: number) { this.items.push(price); }
total() { return this.items.reduce((sum, p) => sum + p, 0); }
pay(card: string, amt: number) { this.paid.push(`${card}: ${amt}`); }
email(to: string) { this.outbox.push(to); }
buy(card: string, to: string) {
const amt = this.total();
this.pay(card, amt);
this.email(to);
return amt;
}
}Why it hurts
- Every change lands in one file. The cart team, the payments team and whoever owns receipts all edit
OrderManager, so they conflict and retest each other's code. - Nothing can be reused or replaced alone. You cannot use the cart without the payment code, or test receipts without building a cart. In the visualizer, every message in the Before run goes from
orderstoorders. - Low cohesion hides in plain sight.
itemsis used only byaddandtotal,outboxonly byemail: the class is really several classes sharing one name. - The cost grows with the class. The SMS change request adds a field, a method and a branch to
OrderManager(8 lines in the class every feature lives in), and the next channel will add another branch.
How to spot it
- A name that promises everything:
Manager,Processor,Util,Helper,Servicewith no noun in front of it. - Groups of fields used by separate groups of methods. Draw which method touches which field: disconnected islands are classes waiting to be extracted.
- It appears in most commits, and most bugs are fixed in it.
- Its tests need a huge setup, or there are none because nobody can build one.
The cure
Apply Extract Class once per island: move items, add and total into Cart, the payment code into Payments, the receipt code behind a Notifier interface. What remains is a thin coordinator, Checkout, that holds the parts and knows the order of the steps. That coordinator is often a Facade; when the parts must talk to each other a lot, a Mediator. Putting the notifier behind an interface is the Strategy pattern, and it is why the SMS change request is one new class instead of an edit. The principle behind all of it is the single responsibility principle from SOLID Principles.
Spaghetti code
Spaghetti code is control flow that cannot be followed: deeply nested conditionals, boolean flags that change what later code does, early exits mixed with shared mutable state, and long functions that do five things in an interleaved order. It is a smell of functions rather than classes, and it often lives inside a God Object.
// Before: the reader has to keep four conditions in their head.
function shippingFee(order: Order): number {
let fee = 0;
if (order.items.length > 0) {
if (!order.pickup) {
if (order.total < 50) {
fee = order.express ? 15 : 5;
} else if (order.express) {
fee = 10;
}
}
}
return fee;
}
// After Replace Nested Conditional with Guard Clauses:
function shippingFeeClear(order: Order): number {
if (order.items.length === 0 || order.pickup) return 0;
if (order.total >= 50) return order.express ? 10 : 0;
return order.express ? 15 : 5;
}The cures are small function-level refactorings: Extract Function for each idea, Decompose Conditional to name complicated conditions, Replace Nested Conditional with Guard Clauses to return early from special cases, and Split Loop or Split Phase when one block does two jobs. When the flags really encode a lifecycle (isPaid, isShipped, isCancelled), the destination is State; when an if-chain decides who handles a request, it is Chain of Responsibility.
Primitive Obsession
Primitive Obsession is using built-in types (string, number, boolean) for ideas that have rules of their own: email addresses, money, phone numbers, date ranges, IDs. The type string says nothing about whether the value was checked, so every class that receives one checks it again, or forgets to.
- The rule is copied. In the visualizer,
Signup,NewsletterandInviteseach lower-case the address and require an@. Adding "trim spaces" means editing all three (9 lines); missing one stores" ana@ok.io"as a different subscriber. - Bad values travel far. The malformed
"bo.ok.io"is a validstring, so it reachesInvites.sendbefore anything objects. - Mix-ups compile.
transfer(amount: number, fee: number)accepts its arguments in the wrong order, andprice + weighttype-checks.
The cure is Replace Primitive with Object (Replace Data Value with Object in the first edition of Fowler's book): a small class, here Email, that normalizes and validates in its constructor. After that, a function that takes an Email can trust it, so the checks disappear from every caller, and the trim rule becomes one edit in one class (3 lines in the visualizer). Such classes are value objects: compared by value, usually immutable, and cheap. Martin Fowler's Money pattern (an amount plus a currency, with arithmetic that refuses to add dollars to euros) is the classic example.
Shotgun Surgery and Divergent Change
Shotgun Surgery is one logical change that forces many small edits in many classes. Its twin, Divergent Change, is one class edited for many unrelated reasons (which is the God Object seen from the change log). A frequent cause of Shotgun Surgery is what Fowler's second edition calls Repeated Switches: the same switch on the same type code, copied into every class that needs to behave differently per type.
class Billing {
bill(plan: string, months: number) {
switch (plan) {
case "free": return 0;
case "pro": return 12 * months;
}
throw new Error(plan);
}
}
// Limits.canAdd(plan, seats) and Support.route(plan) repeat the same
// switch over "free" and "pro". A Team plan means three edits.The cure gathers everything about one plan into one place: Replace Conditional with Polymorphism gives each plan a class (FreePlan, ProPlan) that answers price(), seats() and support(), and the services ask the plan instead of switching. One switch still has to exist, to turn the stored name into an object, and it moves into a single factory method, Plan.of(name) (see Factory Method). In the visualizer, adding the Team plan edits 3 classes in Before and 1 class (the factory) plus 1 new class in After.
More smells you will meet
| Smell | What it looks like | Cure, and where it leads |
|---|---|---|
| Long Function | A function you have to scroll, with comments that separate its parts | Extract Function, Decompose Conditional; Template Method when several functions share one outline |
| Duplicated Code | The same few lines in several places, slowly drifting apart | Extract Function, Pull Up Method; a shared helper or Template Method |
| Long Parameter List | create(a, b, c, d, e, f) and callers passing null for half of them | Introduce Parameter Object, Preserve Whole Object; Builder for many optional parts |
| Feature Envy | A method that reads another object's fields more than its own | Move Function, so behavior sits next to its data (The Four Pillars of OOP) |
| Message Chains | order.getCustomer().getWallet().debit(30) | Hide Delegate; the Law of Demeter in DRY, KISS, YAGNI & the Law of Demeter |
| Middle Man | A class whose methods only forward to another class | Remove Middle Man, Inline Class (a real Proxy adds behavior) |
| Refused Bequest | A subclass that overrides inherited methods to throw or do nothing | Replace Subclass with Delegate; see Composition vs Inheritance |
| Null checks everywhere | if (customer != null) before every use of a possibly missing object | Introduce Special Case; Null Object |
| Global state | A static field or Singleton that any code can read and change | Pass the dependency in (Dependency Injection); see the cautions in Singleton |
| Speculative Generality | Interfaces, hooks and parameters that nothing uses yet | Collapse Hierarchy, Inline Function; YAGNI in DRY, KISS, YAGNI & the Law of Demeter |
| Comments as deodorant | A comment explaining what a confusing block does | Extract Function with a name that says what the comment said |
Anti-patterns above the class level
| Anti-pattern | What happens | The way out |
|---|---|---|
| Big Ball of Mud | No visible architecture: every module calls every other one (named by Brian Foote and Joseph Yoder, 1997) | Draw boundaries and enforce dependency direction (Layered, Hexagonal & Clean Architecture); carve pieces out gradually with Strangler Fig |
| Golden Hammer | One familiar tool or pattern used for every problem, needed or not | Choose by the forces at hand; most patterns lessons here end with "when not to use it" |
| Lava Flow | Dead or experimental code nobody dares to delete because nobody remembers why it is there | Tests plus version control make deletion safe: delete it |
| Anemic Domain Model | Domain classes with only getters and setters, and all logic in services (Fowler, 2003) | Move Function: put behavior next to the data it uses |
| Copy-and-paste programming | Features built by copying a similar one and editing it | Extract the shared part before the third copy (the rule of three) |
| Distributed monolith | Services that must be deployed together because they share tables or call each other synchronously everywhere | Clear ownership (Database per Service) and asynchronous messages |
Finding smells in a real codebase
- 1
Ask the change log
Files that change together in many commits point to Shotgun Surgery; one file in nearly every commit points to a God Object.
git log --name-onlyplus a short script, or a tool built on the same idea, finds both. - 2
Let linters count
Size and complexity limits catch the obvious cases: ESLint's
complexity,max-depthandmax-paramsrules, Pylint'stoo-many-branchesandtoo-many-instance-attributes, PMD'sGodClassrule, and SonarQube's cognitive complexity. - 3
Notice what is hard to test
A class that needs ten collaborators to build, or a function that cannot be tested without a database, is telling you about coupling.
- 4
Watch the next change
The most reliable signal: when a small request needs edits in many places, or edits in a class that has nothing to do with it, the design is fighting the change. Fix the smell that is in the way, as part of that change.
When to fix a smell, and when to leave it
Fix it when
- The change you are making right now has to go through it
- It is the third copy of the same code or the same
switch(the rule of three) - It is where most bugs are reported
- A test would be easy to write afterwards and impossible before
Leave it when
- The code is stable and nobody needs to change it
- It is about to be deleted or replaced
- There are no tests and no way to add any yet (add them first)
- The "smell" is the clearest way to express a simple, fixed rule
Implementation
The visualizer's God Object scenario as a complete program. OrderManager does everything; after Extract Class, Cart, Payments and an EmailNotifier behind the Notifier interface each do one job and Checkout coordinates them. The demo runs the same purchase through both versions and prints identical output.
from abc import ABC, abstractmethod
# Before: one class keeps the cart, charges the card and sends receipts.
class OrderManager:
def __init__(self) -> None:
self._items: list[int] = []
def add(self, price: int) -> None:
self._items.append(price)
def total(self) -> int:
return sum(self._items)
def pay(self, card: str, amt: int) -> None:
print(f"charged {amt} to card {card}")
def email(self, to: str) -> None:
print(f"receipt sent to {to}")
def buy(self, card: str, to: str) -> int:
amt = self.total()
self.pay(card, amt)
self.email(to)
return amt
# After: one class per job, and a thin coordinator.
class Cart:
def __init__(self) -> None:
self._items: list[int] = []
def add(self, price: int) -> None:
self._items.append(price)
def total(self) -> int:
return sum(self._items)
class Payments:
def pay(self, card: str, amt: int) -> None:
print(f"charged {amt} to card {card}")
class Notifier(ABC):
@abstractmethod
def send(self, to: str) -> None: ...
class EmailNotifier(Notifier):
def send(self, to: str) -> None:
print(f"receipt sent to {to}")
# SMS receipts later: one new class, no existing class edited.
class SmsNotifier(Notifier):
def send(self, to: str) -> None:
print(f"text sent to {to}")
class Checkout:
def __init__(self, cart: Cart, payments: Payments,
notifier: Notifier) -> None:
self._cart = cart
self._payments = payments
self._notifier = notifier
def buy(self, card: str, to: str) -> int:
amt = self._cart.total()
self._payments.pay(card, amt)
self._notifier.send(to)
return amt
if __name__ == "__main__":
print("-- before")
orders = OrderManager()
orders.add(30)
orders.add(15)
print("total", orders.buy("4242", "ana@ok.io"))
print("-- after")
cart = Cart()
cart.add(30)
cart.add(15)
checkout = Checkout(cart, Payments(), EmailNotifier())
print("total", checkout.buy("4242", "ana@ok.io"))
# Both halves print:
# charged 45 to card 4242
# receipt sent to ana@ok.io
# total 45Key takeaways
- A code smell is a symptom worth investigating, not a rule violation. Judge it by what it costs when the code has to change.
- God Object: one class with many unrelated jobs. Cure it with Extract Class, leaving a thin coordinator (often a Facade); in the visualizer, SMS receipts cost 8 lines in the god class and one new class after the split.
- Primitive Obsession: a domain idea passed around as a bare string or number. A value object checks once and lets every caller trust it; the trim rule went from 3 classes and 9 lines to 1 class and 3 lines.
- Shotgun Surgery, often from repeated switches on a type code: one change, many edits. Replace Conditional with Polymorphism gathers each type into one class; a new plan went from 3 edited classes to 1 new class plus one factory case.
- Most smells have a named refactoring and a destination pattern: Strategy and State for conditionals, Null Object for null checks, Dependency Injection for global state, Template Method for duplicated outlines.
- Fix the smell that is in the way of the current change, in small steps with tests, instead of planning a big clean-up.
Common pitfalls
- Treating smells as hard rules: splitting a cohesive 200-line class into five anemic ones, or replacing a stable two-branch
ifwith an interface and three classes. The Golden Hammer applies to patterns too. - Curing a God Object by moving its methods into static utility classes. The code is spread out, but the data and the behavior are still separated and everything still depends on everything.
- Moving a
switchinstead of removing its copies: polymorphism leaves exactly one switch (in a factory or at the edge where data comes in), not one per new class. - Refactoring without tests. Without a safety net, a "clean-up" changes behavior silently; write characterization tests first (see Refactoring Toward Patterns).
- Mixing a refactoring with a behavior change in one commit, so a reviewer cannot tell which line did what and a revert removes both.
Interview tips
- When shown a messy class in an LLD or code-review round, name the smell first ("this is a God Object, the fields split into three groups"), then the refactoring (Extract Class), then the pattern it leads to. Names show you know the catalog; the reasoning shows judgment.
- Quantify the cost: "adding a plan touches these three switches" is more convincing than "it violates OCP". Then show the version where the same change is one new class.
- Be ready to argue the other side: say when you would leave the smell alone (stable code, two branches, no tests yet) and when polymorphism makes the opposite change expensive.
Real-world applications
- Code review checklists: oversized classes, repeated switches, long parameter lists and null checks are the most common review comments.
- Static analysis gates in CI: complexity, function length, parameter count and class size limits in ESLint, Pylint, PMD, Checkstyle or SonarQube.
- Legacy modernization: finding the God Objects and repeated switches that block a feature, and carving them out first.
- Value objects such as Java's
java.timetypes (LocalDate,Duration) and Money types, which replace raw numbers and strings for dates, durations and amounts. - Technical-debt planning: ranking smells by how often the code around them changes, so clean-up effort goes where changes actually happen.
Test yourself
In the visualizer's God Object scenario, what does the "Add SMS receipts" change request cost in each version?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.