Code Smells and Refactoring
The warning signs an interviewer spots in a design — the god class, the switch on type, money as a double, the method that reaches through three objects — and the small, named refactoring that removes each one.
A code smell is a sign that something is probably wrong — not a bug, not a crash, just a shape that tends to cause trouble later. The word is useful because it's honest: a smell is a reason to look closer, not proof.
This matters in interviews twice. First, interviewers notice smells in your design, and fixing one before they point it out is a strong signal. Second, some rounds hand you a messy snippet and ask "what would you change?" — a direct test of whether you can name problems and fix them in order.
The fixes have names too. Each one is a refactoring: a small change to the structure of code that doesn't change what it does. Knowing the names lets you say "I'd extract a class here" instead of waving your hands.
#The god class
The smell: one class that does everything. ParkingService that finds spots, calculates prices, prints tickets, talks to the payment gateway and sends emails. It's 900 lines long and every change touches it.
Why it hurts: every reason to change the system becomes a reason to change this file. Two people can't work on it at once, and a fix to pricing can break emails.
The fix — Extract Class. Find groups of fields and methods that are used together, and move each group into its own class.
// Before: one class, five jobs
class ParkingService {
Ticket park(Vehicle v) { /* find spot, assign, print, notify */ }
Money leave(Ticket t) { /* compute price, charge card, email receipt */ }
private Money computePrice(Ticket t) { ... }
private void chargeCard(Money m, Card c) { ... }
private void emailReceipt(Ticket t, Money m) { ... }
}
// After: each job has a home; ParkingService only coordinates
class ParkingService {
private final SpotAllocator allocator;
private final PricingPolicy pricing;
private final PaymentGateway payments;
private final Notifier notifier;
...
}This is the single responsibility principle in action. The test for "is this one job?": can you describe the class without the word and?
#The switch on type
The smell: the same switch (or if/else chain) over a type code, repeated in several places.
Money price(Vehicle v, Duration d) {
switch (v.type()) {
case CAR: return Money.of(40 * d.toHours());
case BIKE: return Money.of(20 * d.toHours());
case TRUCK: return Money.of(100 * d.toHours());
default: throw new IllegalStateException();
}
}
// ...and another switch in canFit(), and another in describe()Why it hurts: adding ELECTRIC_CAR means finding every switch. Miss one and it fails at runtime, maybe months later.
The fix — Replace Conditional with Polymorphism. Move each branch into the type it belongs to, or into a strategy when the behaviour should be swappable on its own.
abstract class Vehicle {
abstract Money hourlyRate();
abstract boolean fits(SpotSize s);
}
class Car extends Vehicle {
Money hourlyRate() { return Money.of(40); }
boolean fits(SpotSize s) { return s != SpotSize.SMALL; }
}A new vehicle is now a new class. Nothing else changes — the open/closed principle without the jargon.
#Primitive obsession
The smell: using raw strings and numbers for things that have rules. Money as double. An email as String. A seat as int row, int col passed everywhere as a pair.
Why it hurts: the rules have nowhere to live, so they're repeated (or forgotten) at every use. double money drifts by fractions of a paisa, because a double can't store most decimals exactly — in Java, 0.1 + 0.2 gives 0.30000000000000004, and those tiny errors add up across thousands of transactions. A String email can hold "hello".
The fix — Replace Primitive with Object. Make a small value class that enforces the rule once.
record Email(String value) {
Email {
if (!value.matches("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$"))
throw new IllegalArgumentException("not an email: " + value);
}
}
record Money(long minor, Currency currency) { ... } // whole paise, never doubleNow an Email that exists is valid by definition, because the constructor refuses to create a bad one. And a method that takes Money can't be handed a temperature by accident — a method taking a bare double would accept any number at all. This is the cheapest improvement you can make to an LLD answer, and the one interviewers notice most — see how Splitwise uses Money.
#Long parameter lists and data clumps
The smell: a method with six parameters, or the same three values always travelling together.
Booking book(String showId, int row, int col,
String userId, String email, boolean premium)row and col always go together. So do userId and email. These are data clumps — groups that want to be an object.
The fix — Introduce Parameter Object. Name the clump.
record SeatRef(int row, int col) { }
Booking book(ShowId show, SeatRef seat, Customer customer, Tier tier)Fewer parameters, and each one now has a type that explains itself. When construction itself takes many optional values, a builder is the next step.
#Feature envy
The smell: a method that's more interested in another class's data than its own.
class InvoicePrinter {
String line(Order o) {
long total = 0;
for (Item i : o.items()) total += i.price() * i.qty();
if (o.customer().isPremium()) total = total * 90 / 100;
return "Total: " + total;
}
}InvoicePrinter is doing Order's arithmetic. If the discount rule changes, you have to know to look in the printer.
The fix — Move Method. Put the calculation on the class that owns the data.
class Order {
Money total() { ... } // the rule lives next to the data it uses
}
class InvoicePrinter {
String line(Order o) { return "Total: " + o.total(); }
}#Reaching through objects
The smell: a chain of calls that walks through several objects.
String city = booking.getCustomer().getAddress().getCity();This line knows that bookings have customers, customers have addresses, and addresses have cities. Change any link — say, a customer gets a list of addresses instead of one — and this line breaks, along with every other line like it. The rule it breaks has a name — the Law of Demeter: talk to your friends, not to your friends' friends. In code: call methods on objects you hold directly (booking), not on objects you dug out of them (booking's customer's address).
The fix — Hide Delegate. Ask the nearest object for what you need and let it decide how to get it.
String city = booking.customerCity();Don't overdo it. Some chains are fine: reading plain settings data (config.db().url()), or a fluent builder where each call returns the same builder so you can chain them (builder.name("x").size(3).build()). The smell is when the chain walks through the internal structure of several real objects — structure that, if it changed, would force edits in many places.
#Boolean flag arguments
The smell: render(document, true) — what does true mean?
Why it hurts: a flag usually means the method does two different things, and every caller has to know which is which.
The fix: split it into two well-named methods — renderPreview(doc) and renderFull(doc) — or use an enum when there really are several modes.
#Shotgun surgery and divergent change
Two smells that are mirror images, and worth naming as a pair:
- Shotgun surgery: one change forces edits in many classes. Adding a currency means touching
Order,Invoice,Refund,ReportandLedger. The fix is to gather the scattered logic into one place — often a value object likeMoney. - Divergent change: one class changes for many unrelated reasons.
UserServicechanges for login rules, for profile fields, and for email templates. The fix is to split it. This is really the god class again — just noticed from the change history ("why does this file change every week?") rather than from reading it.
#Duplicated code — with a caution
The smell: the same logic in two places. They'll drift apart, and a bug fixed in one stays in the other.
The fix — Extract Method, or Extract Class if the duplicate is larger.
The caution: two pieces of code that look the same today aren't always the same idea. Suppose a tax calculation and a shipping calculation both happen to multiply by 1.18. Merge them into one method, and the day the tax rate changes, shipping prices change with it by accident — you've tied together two things that change for different reasons. A common rule of thumb is the rule of three: tolerate it twice, extract it the third time.
#The opposite smell: building for a future that never comes
Speculative generality is the smell of over-engineering — an interface with one implementation and no second in sight, an abstract factory for objects that never vary, configuration for things nobody configures.
In an interview this is the more common failure. Candidates who have just learned patterns use six of them on a vending machine. An interface earns its place when there's a real, named second case — "pricing differs on weekends" — not when "it might change someday".
#Refactoring safely
The point of refactoring is to change structure without changing behaviour. That only works in small steps:
- Have a test that pins down current behaviour before you start — even a rough one.
- Make one named change — extract a method, move a field.
- Run the tests. Green means the behaviour is unchanged.
- Repeat. Commit often, so any step can be undone.
Big rewrites fail because nobody can tell which of forty changes broke something. Forty small refactorings, each tested, almost never do.
#In the interview
When reviewing a snippet, work in this order, and say each item aloud:
- Correctness first — bugs, races, money as
double, missing validation. - Then the biggest structural smell — usually a god class or a repeated switch.
- Then the small ones — names, flag arguments, long parameter lists.
- Name the refactoring for each: "extract class", "replace conditional with polymorphism", "introduce parameter object".
In your own design, leave yourself a line for the end: "With more time I'd pull the notification code out of the service into its own class — it's the next thing that will change." It shows you can see your own design's weak point, which is exactly what a senior engineer does.
#Check yourself
What is a code smell?Show answer
God class — the smell and the fix?Show answer
Repeated switch on type — the smell and the fix?Show answer
What is primitive obsession, and the fix?Show answer
Feature envy and reaching through objects — the fixes?Show answer
Shotgun surgery versus divergent change?Show answer
What is speculative generality, and the safe sentence?Show answer
In what order do you review a snippet?Show answer
#What to carry forward
- A smell is a reason to look closer; each has a named refactoring.
- God classes and repeated switches are the big structural smells; Extract Class and polymorphism fix them.
- Value objects such as Money and Email are the cheapest upgrade to any design.
- Over-engineering is a smell too — add an interface only for a real, named second case.
- Refactor in small, tested steps; review correctness first, then structure, then details.