- Chapter
- Chapter 2 — Code Smells
- Prerequisites
- Chapter 1
- You will be able to
- Recognise long methods, large classes and long parameter lists, understand why they grow, measure them with sensible thresholds, and apply the refactorings that shrink them — Extract Method, Extract Class, Introduce Parameter Object and Preserve Whole Object
- Covers
- Long method; Large class; Large parameter list
On this page
- 1. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally — Detecting Bloaters
- 4A. Deep Dive — Why Bloaters Keep Growing (and How to Stop It)
- 5. APIs / Features / Syntax
- 6. Practical Examples
- 7. Common Problems & Mistakes
- 8. Performance & Production Considerations
- 9. Architecture & Design Considerations
- 10. Interview Questions & Answers
1Concept / Definition
Bloaters are code elements that have grown so large they are hard to understand and change. They rarely appear at once; they accumulate as each change adds "just a few more lines" to an existing method, class or signature.
| Bloater | Symptom | Typical threshold (guideline) |
|---|---|---|
| Long method | Many lines, comments as section headings, deep nesting | > 20–30 lines or cognitive complexity > 15 |
| Large class | Many fields and methods, several responsibilities | > 300–500 lines, > 10–15 fields, > 20–30 methods |
| Large parameter list | Many parameters, especially of the same type | > 3–4 parameters (Sonar default: 7) |
| Data clumps | Same group of values passed or stored together | Appears in 3+ places |
| Primitive obsession | Strings/numbers representing domain concepts | See Topic 2.4 |
2Why It Exists
Adding to an existing method or class is always the path of least resistance: the context is already there, and creating a new unit requires naming it and deciding where it belongs. Deadlines reward the shortcut; nobody removes lines later. Over years, a 20-line method becomes 300 lines and an OrderService becomes the place where everything order-related lives. Bloaters are the most common smell in enterprise Java code — and the easiest to detect mechanically.
3Core Concepts
3.1 Long method

Long methods mix several levels of abstraction and responsibilities: validation, calculation, persistence, notification. They are hard to name accurately, hard to test and hard to reuse.
// Before — 70 lines in reality; abbreviated here
public void processOrder(Order order) {
// validate
if (order.getLines().isEmpty()) throw new IllegalArgumentException("empty order");
for (OrderLine l : order.getLines()) {
if (l.getQuantity() <= 0) {
throw new IllegalArgumentException("bad qty " + l.getSku());
}
if (!catalog.exists(l.getSku())) {
throw new IllegalArgumentException("unknown " + l.getSku());
}
}
// price
BigDecimal total = BigDecimal.ZERO;
for (OrderLine l : order.getLines()) {
BigDecimal price = catalog.price(l.getSku());
total = total.add(price.multiply(BigDecimal.valueOf(l.getQuantity())));
}
// discount
if (order.getCustomer().isVip()) total = total.multiply(new BigDecimal("0.90"));
else if (total.compareTo(new BigDecimal("5000")) > 0) {
total = total.subtract(new BigDecimal("250"));
}
order.setTotal(total.setScale(2, RoundingMode.HALF_EVEN));
// persist + notify
orderRepository.save(order);
mailer.send(order.getCustomer().getEmail(), "Order received",
"Total: " + order.getTotal());
}// After — composed method: each line one step, one level of abstraction
public void processOrder(Order order) {
validate(order);
order.setTotal(roundToCents(applyDiscounts(order, subtotal(order))));
orderRepository.save(order);
confirmationMailer.orderReceived(order);
}
private void validate(Order order) {
if (order.getLines().isEmpty()) throw new IllegalArgumentException("empty order");
order.getLines().forEach(this::validateLine);
}
private void validateLine(OrderLine l) {
if (l.getQuantity() <= 0) throw new IllegalArgumentException("bad qty " + l.getSku());
if (!catalog.exists(l.getSku())) {
throw new IllegalArgumentException("unknown " + l.getSku());
}
}
private BigDecimal subtotal(Order order) {
return order.getLines().stream()
.map(l -> catalog.price(l.getSku())
.multiply(BigDecimal.valueOf(l.getQuantity())))
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
private BigDecimal applyDiscounts(Order order, BigDecimal subtotal) {
if (order.getCustomer().isVip()) return subtotal.multiply(VIP_FACTOR);
if (subtotal.compareTo(BULK_THRESHOLD) > 0) return subtotal.subtract(BULK_REBATE);
return subtotal;
}| Long-method signal | Refactoring |
|---|---|
| Comment introduces a block | Extract Method named after the comment |
| Conditional with complex branches | Decompose Conditional |
| Loop computing a value | Extract Method / Replace Loop with Pipeline |
| Many temporaries | Replace Temp with Query; Replace Method with Method Object |
| Different abstraction levels mixed | Composed Method pattern |
3.2 Large class

A large ("god") class has many fields and methods serving several responsibilities. Symptoms: methods that use disjoint subsets of fields, names with prefixes (invoiceX, mailY), frequent merge conflicts because everyone edits the same file.
// Before: one class, four responsibilities
@Service
public class OrderManager {
private final OrderRepository orders;
private final ProductCatalog catalog;
private final TaxTables taxTables;
private final JavaMailSender mail;
private final PdfEngine pdf;
public Order create(…) { … }
public BigDecimal price(Order o) { … } // pricing
public BigDecimal tax(Order o) { … } // tax
public byte[] invoicePdf(Order o) { … } // rendering
public void emailInvoice(Order o) { … } // notification
// … 40 more methods
}// After: cohesive classes, each with one reason to change
@Service class OrderService { /* create, cancel — uses orders, pricing, tax */ }
@Component class PricingPolicy { /* price(Order) — uses catalog */ }
@Component class TaxPolicy { /* tax(Order) — uses taxTables */ }
@Component class InvoiceRenderer { /* pdf(Order) — uses pdf engine */ }
@Component class CustomerNotifier { /* emailInvoice(Order) — uses mail */ }| Large-class signal | Refactoring |
|---|---|
| Subsets of fields used by subsets of methods | Extract Class (Topic 3.2) |
| Behaviour only for some instances | Extract Subclass / sealed variants |
| Many static helper methods | Move Method to the classes they operate on |
| UI/controller class containing business logic | Extract service/domain classes |
3.3 Large parameter list

Long parameter lists are hard to call correctly (argument order), hard to change (every caller updates) and often hide missing concepts.
// Before
public List<Hotel> search(LocalDate checkIn, LocalDate checkOut, String city,
int adults, int children,
BigDecimal minPrice, BigDecimal maxPrice,
int minStars, boolean breakfast, int page, int size) { … }
// which number is which?
search(from, to, "Pune", 2, 0, null, new BigDecimal("8000"), 4, true, 0, 20);// After: parameter objects (records) with validation and meaning
public record StayDates(LocalDate checkIn, LocalDate checkOut) {
public StayDates {
if (!checkOut.isAfter(checkIn)) {
throw new IllegalArgumentException("checkOut must be after checkIn");
}
}
public long nights() { return ChronoUnit.DAYS.between(checkIn, checkOut); }
}
public record Guests(int adults, int children) { }
public record PriceRange(BigDecimal min, BigDecimal max) { }
public record HotelFilter(PriceRange price, int minStars, boolean breakfast) { }
public Page<Hotel> search(String city, StayDates dates, Guests guests,
HotelFilter filter, PageRequest page) { … }| Parameter-list signal | Refactoring |
|---|---|
| Values always passed together | Introduce Parameter Object (Topic 3.5) |
| Values taken from one object | Preserve Whole Object |
| Boolean flag parameter | Split into two methods |
| Parameter derivable by the callee | Replace Parameter with Query |
| Many optional parameters | Builder or record with defaults |
4How It Works Internally — Detecting Bloaters

| Tool | Rule / feature |
|---|---|
| SonarQube | S138 (method too long), S1448 (too many methods), S107 (too many parameters), S3776 (cognitive complexity) |
| PMD | ExcessiveMethodLength, GodClass, ExcessiveParameterList, TooManyFields |
| Checkstyle | MethodLength, ParameterNumber, ClassFanOutComplexity |
| IntelliJ inspections | "Overly long method", "Class with too many methods", "Method with too many parameters" |
| Git history | Files with the most commits and merge conflicts |
Use tools to find candidates; use judgement to decide. A 60-line method that builds a simple, flat mapping may be fine; a 25-line method with four nested levels is not.
4ADeep Dive — Why Bloaters Keep Growing (and How to Stop It)
| Force | Countermeasure |
|---|---|
| Adding to existing code is easiest | Boy Scout rule: extract before adding |
| Fear of creating new classes ("class explosion") | Records make small types cheap; packages organise them |
Framework habits (one @Service per entity) | Model behaviour in domain objects and policies |
| Code ownership by file | Collective ownership; smaller files reduce conflicts |
| No quality gate on new code | Sonar gate: no new methods above complexity threshold |
Composed Method pattern (Beck): divide a program into methods that each perform one identifiable task, and keep all operations in a method at the same level of abstraction. It is the target shape for long methods.
Method Object (Replace Method with Method Object): when a long method has many local variables that prevent extraction, turn the method into its own class whose fields are the former locals — then extract freely inside it.
// Replace Method with Method Object
class PremiumCalculation {
private final Policy policy; private final Driver driver;
private BigDecimal base, loading, discount; // former locals
PremiumCalculation(Policy policy, Driver driver) {
this.policy = policy;
this.driver = driver;
}
BigDecimal compute() {
base = basePremium();
loading = ageLoading().add(claimsLoading());
discount = noClaimsDiscount();
return base.add(loading).subtract(discount);
}
// small private methods can now share state without long parameter lists
}5APIs / Features / Syntax
| Feature | Use against bloaters |
|---|---|
| Records | Cheap parameter objects and value objects |
| Compact constructors | Validation inside parameter objects |
| Streams | Replace accumulating loops with pipelines |
| Sealed interfaces | Split variant behaviour out of large classes |
| IntelliJ: Extract Method (⌥⌘M), Extract Delegate, Introduce Parameter Object | Automated cures |
| SonarLint in IDE | Immediate feedback on size and complexity |
6Practical Examples
6.1 Spring controller bloat
A 400-line @RestController with validation, mapping, business rules and error handling was reduced to 60 lines by moving validation into request records (Bean Validation), mapping into assemblers, rules into a service and errors into a @RestControllerAdvice.
6.2 Preserve Whole Object
// Before
double fee = feeCalculator.fee(order.getCountry(), order.getWeight(), order.isExpress());
// After
double fee = feeCalculator.fee(order); // callee picks what it needsTrade-off: the callee now depends on Order. Prefer this when the callee conceptually works on orders; otherwise introduce a small parameter object.
6.3 Worked example — shrinking a god class step by step
CustomerAccountService: 1,850 lines, 23 fields, 96 methods, touched by 70% of tickets in its module.
| Step | Refactoring | Result |
|---|---|---|
| 1 | Field-usage analysis (IntelliJ "Dependency Structure", manual matrix) | 5 clusters: profile, addresses, loyalty, preferences, GDPR export |
| 2 | Characterisation tests for public methods used by controllers | Safety net |
| 3 | Extract Class LoyaltyAccount (fields + 18 methods) | Service delegates |
| 4 | Extract Class AddressBook, NotificationPreferences | Two more collaborators |
| 5 | Move GDPR export to PersonalDataExporter | Separate module later |
| 6 | Inline delegating methods; controllers call new classes directly | Service down to profile use cases |
| Metric | Before | After |
|---|---|---|
| Largest class | 1,850 lines | 420 lines |
| Merge conflicts in module per month | ~14 | ~3 |
| Median lines changed per ticket | 180 | 70 |
6.4 Worked example — measuring bloat in CI
<!-- PMD rules in the build: fail on NEW violations only (baseline existing ones) -->
<rule ref="category/java/design.xml/GodClass"/>
<rule ref="category/java/design.xml/ExcessiveParameterList">
<properties><property name="minimum" value="6"/></properties>
</rule>
<rule ref="category/java/design.xml/CognitiveComplexity">
<properties><property name="reportLevel" value="15"/></properties>
</rule>| Policy | Effect |
|---|---|
| Baseline existing violations | Build not blocked by legacy |
| Fail on new violations | Bloat stops growing |
| Report trend per sprint | Visible progress as legacy violations are refactored away |
The clean-as-you-code approach (quality gate on new and changed code) is far more effective than trying to fix all legacy bloat at once.
6.5 Worked example — decomposing a long method with many locals
A 140-line calculatePremium had 14 local variables used across the whole body, so Extract Method produced methods with 6–8 parameters. Applying Replace Method with Method Object first (moving locals to fields of PremiumCalculation) allowed extraction into 11 small methods with no parameters, after which several of them moved into Driver and Policy (Move Method, Topic 3.3).
| Stage | Largest method | Parameters per extracted method |
|---|---|---|
| Original | 140 lines | — |
| Extract Method directly | 40 lines | 6–8 (unreadable) |
| Method Object, then Extract | 18 lines | 0–1 |
| Move Method into domain objects | 12 lines | 0–1 |
7Common Problems & Mistakes
- Mechanical splitting by line count — methods named
part1,part2. - Extracting into "Helper" or "Utils" classes instead of meaningful homes.
- Parameter objects without meaning (
Params1) — just moving the problem. - Splitting classes by technical layer only, leaving business responsibilities mixed.
- Fixing all legacy bloat at once — risky, unfundable; use clean-as-you-code.
- Ignoring tests when decomposing god classes.
8Performance & Production Considerations
| Concern | Reality |
|---|---|
| Many small methods | JIT inlines; negligible cost |
| More objects (parameter objects) | Short-lived; escape analysis often eliminates them |
| Large classes in Spring | Large beans with many dependencies slow startup and tests |
| Operational diagnosis | Small, named methods produce clearer stack traces |
Breaking bloaters apart almost never costs runtime performance on a modern JVM: small methods are inlined by the JIT, and short-lived parameter records are often scalar-replaced by escape analysis, so they are never allocated on the heap. Very large methods are the real risk. HotSpot by default refuses to JIT-compile methods whose bytecode exceeds 8,000 bytes (the DontCompileHugeMethods setting), so a generated or hand-grown giant method can stay interpreted and run many times slower than its split equivalent. In Spring, a god bean with twenty dependencies widens the part of the application context that tests must load, slowing every integration test and making test slices such as @WebMvcTest harder to use. Operationally, small named methods produce stack traces and profiler flame graphs that point to a specific step, and smaller classes reduce merge conflicts and the blast radius of each deployment.
9Architecture & Design Considerations
- Enforce size and complexity limits on new code via quality gates.
- Use records and sealed types to make new small types cheap.
- Decompose god classes along business responsibilities, aligning with bounded contexts.
- Watch merge-conflict hotspots as a sign of bloated shared classes.
10Interview Questions & Answers
What are bloaters?
Bloaters are code smells in which a method, class or parameter list has grown so large that it is hard to understand and change. The main ones are long methods, large or god classes and long parameter lists, with data clumps and primitive obsession closely related. They rarely appear at once: each change adds a few more lines to an existing unit because that is the path of least resistance, and nobody removes them later. Thresholds such as 20 to 30 lines per method or a cognitive complexity above 15 help find candidates, but the real test is whether a teammate can understand the unit in one reading and whether it changes for one reason.
What is the main cure for a long method?
Extract Method: take a cohesive fragment, often a block introduced by a comment such as validate or price, and move it into a private method named after what it does, passing in only what it needs. Repeated across the method, this produces the Composed Method shape, where the original reads as a short sequence of steps at one level of abstraction, such as validate, subtotal, applyDiscounts and save. IntelliJ automates the refactoring safely, inferring parameters and return values. Related cures handle harder cases: Decompose Conditional for complex branches, Replace Loop with Pipeline for accumulations, and Replace Method with Method Object when too many locals block extraction.
How do you find a split for a large class?
I look for cohesion clusters: groups of fields that are used together by a subset of methods and not by the others. A field-usage matrix, an IntelliJ dependency analysis or LCOM-style metrics make this visible, and a god class usually has three to six clusters. Naming clues help too, such as methods prefixed invoice or mail, or comments separating sections. Then I check reasons to change: which tickets, teams or business rules drive edits to each cluster, using git history. Each cluster with its own reason to change becomes a candidate class, such as PricingPolicy or InvoiceRenderer, extracted one at a time behind characterisation tests.
What are the cures for long parameter lists?
The main cure is Introduce Parameter Object: values always passed together, such as check-in and check-out dates, become a record like StayDates, which can validate itself in its compact constructor and gain behaviour such as nights(). Preserve Whole Object passes the order itself instead of three values read from it, when the callee conceptually works on orders. Replace Parameter with Query removes arguments the callee can derive for itself. A boolean flag parameter usually means two methods should exist, so split it. Many optional parameters suit a builder or a record with sensible defaults. The aim is fewer, meaningful parameters that make a wrong argument order impossible.
What is the Composed Method pattern?
Composed Method, described by Kent Beck, is the target shape for long methods. You divide the logic into methods that each perform one identifiable task, and keep all statements within a method at the same level of abstraction. A top-level method such as processOrder then reads like a summary: validate the order, calculate the subtotal, apply discounts, round, save and send the confirmation, with each step's detail in a well-named private method or collaborator. Readers understand intent without scanning every line, and each step can be tested or changed in isolation. Mixing levels, for example a loop over order lines next to a call that sends email, is the signal to extract.
When would you use Replace Method with Method Object?
When a long method has many local variables that are read and written throughout its body, so Extract Method keeps producing methods with six to eight parameters or several return values. Replace Method with Method Object turns the method into its own class: the original parameters become constructor arguments, the locals become fields, and the body moves into a single compute method. Now any fragment can be extracted into a parameterless private method that shares state through fields. After that, some of those methods often turn out to belong in domain objects, such as Driver or Policy, and can be moved there. It is a stepping stone, not the final design.
How do you stop bloat from growing in a large codebase?
I stop the growth first and fix legacy code gradually, because big clean-up projects are risky and rarely funded. A quality gate on new and changed code, such as SonarQube's clean-as-you-code approach or PMD with existing violations baselined, fails the build when new methods exceed complexity or size limits, while old code does not block delivery. The Boy Scout rule asks developers to extract before adding to an already large unit. Records and sealed types make new small types cheap, collective ownership reduces the one big file everyone edits, and reviews ask where new code belongs. I track legacy violations and merge-conflict hotspots each sprint to show progress.
How do god classes affect architecture?
A god class becomes an unplanned architectural hub. Because it concentrates unrelated responsibilities, nearly every feature must change it, so it becomes a bottleneck for parallel work, a source of merge conflicts and a point of risky deployments. It couples concepts that should evolve independently, and its many dependencies make it hard to test or to move into another module. The real architecture is then whatever the god class forces, rather than the intended boundaries, and any later extraction of modules or services has to split it first. Architects prevent this with quality gates and with clear responsibility boundaries, aligned with bounded contexts, into which code can move.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.