Code Smells
Small, recognisable warning signs, and the refactorings that remove them.
A code smell is not a bug. It is a sign that the code will be harder to change than it needs to be: a method that scrolls forever, a parameter list nobody can read, a switch copied into five files, or names that need a comment to explain them.
Each smell has well-known refactorings, often mechanical ones such as extracting a method, introducing a parameter object or replacing a condition with polymorphism. The skill is spotting the smell and choosing the smallest change that removes it, without changing behaviour.
You'll recognise it when
- Methods with comment banners separating their sections.
- Three values that always travel together as separate parameters.
- Booleans passed in to switch a method between different behaviours.
- Unexplained numbers and strings in business rules.
Example
An airline books seats with a method that grew one argument at a time.
book("Asha Rao", "asha@mail.in", "BLR", "DEL", 2, 1, true, false);
// ^ ^ ^ ^
// adults, children, meal?, window?Passenger asha = new Passenger("Asha Rao", "asha@mail.in");
Route route = new Route("BLR", "DEL");
Party party = Party.of(2).withChildren(1);
book(asha, route, party, Preferences.none().withMeal());Why it's better: Related values travel as one named object, the call explains itself without comments, and swapping two arguments becomes a compile error instead of a wrong booking.
Ideas you'll practise
Problems 21
- SM-21Unexplained Numbers in Loan RulesL1EasyFREE
- SM-02The Order Method That Scrolls ForeverL1EasyComing soon
- SM-03Signing Up Takes Twelve ArgumentsL1EasyComing soon
- SM-04Status as Magic StringsL1EasyComing soon
- SM-05A Method in the Wrong ClassL1MediumComing soon
- SM-06street, city, zip Travel TogetherL1EasyComing soon
- SM-07The Same Switch in Five FilesL1MediumComing soon
- SM-09One Class, Five Reasons to ChangeL1MediumComing soon
- SM-10Subclasses That Override to ThrowL1MediumComing soon
- SM-11A Class That Only DelegatesL3EasyComing soon
- SM-12Two Classes Reading Each Other's PrivatesL1MediumComing soon
- SM-13An Abstract Base With One ChildL3EasyComing soon
- SM-14One Algorithm, Two Copies, DriftingL1EasyComing soon
- SM-16Fields Only Set During One MethodL1MediumComing soon
- SM-18Comments Explaining Bad NamesL1EasyComing soon
- SM-19Half the Branches Never RunL1EasyComing soon
- SM-20Three Booleans Steer One MethodL1EasyComing soon
- SM-22try/catch as if/elseL1MediumComing soon
- SM-28Factories That Build FactoriesL3MediumComing soon
- SM-30Ifs Nested Eight Levels DeepL1EasyComing soon
- SM-31Getters That Change StateL1MediumComing soon