ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 5 · Software Design & Design Patterns
  4. Volume VI
  5. Bloaters
Book 5 · Volume VI — Refactoring, Code Quality & Evolutionary Design · Topic 2.1

Bloaters

Long method, large class and large parameter list

10 min readStage 2 · Frameworks & design8 interview questions
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. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — Detecting Bloaters
  5. 4A. Deep Dive — Why Bloaters Keep Growing (and How to Stop It)
  6. 5. APIs / Features / Syntax
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 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.

BloaterSymptomTypical threshold (guideline)
Long methodMany lines, comments as section headings, deep nesting> 20–30 lines or cognitive complexity > 15
Large classMany fields and methods, several responsibilities> 300–500 lines, > 10–15 fields, > 20–30 methods
Large parameter listMany parameters, especially of the same type> 3–4 parameters (Sonar default: 7)
Data clumpsSame group of values passed or stored togetherAppears in 3+ places
Primitive obsessionStrings/numbers representing domain conceptsSee Topic 2.4
Table 1 — Bloaters at a glance

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 method → composed method
Figure 1 — Long method → composed 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.

JAVA
// 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());
}
JAVA
// 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 signalRefactoring
Comment introduces a blockExtract Method named after the comment
Conditional with complex branchesDecompose Conditional
Loop computing a valueExtract Method / Replace Loop with Pipeline
Many temporariesReplace Temp with Query; Replace Method with Method Object
Different abstraction levels mixedComposed Method pattern
Table 2 — Cures for long methods

3.2 Large class

Large class → cohesive classes
Figure 2 — Large class → cohesive classes

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.

JAVA
// 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
}
JAVA
// 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 signalRefactoring
Subsets of fields used by subsets of methodsExtract Class (Topic 3.2)
Behaviour only for some instancesExtract Subclass / sealed variants
Many static helper methodsMove Method to the classes they operate on
UI/controller class containing business logicExtract service/domain classes
Table 3 — Cures for large classes

3.3 Large parameter list

Long parameter list vs parameter object
Figure 3 — Long parameter list vs parameter object

Long parameter lists are hard to call correctly (argument order), hard to change (every caller updates) and often hide missing concepts.

JAVA
// 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);
JAVA
// 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 signalRefactoring
Values always passed togetherIntroduce Parameter Object (Topic 3.5)
Values taken from one objectPreserve Whole Object
Boolean flag parameterSplit into two methods
Parameter derivable by the calleeReplace Parameter with Query
Many optional parametersBuilder or record with defaults
Table 4 — Cures for long parameter lists

4How It Works Internally — Detecting Bloaters

Bloaters and their cures
Figure 4 — Bloaters and their cures
ToolRule / feature
SonarQubeS138 (method too long), S1448 (too many methods), S107 (too many parameters), S3776 (cognitive complexity)
PMDExcessiveMethodLength, GodClass, ExcessiveParameterList, TooManyFields
CheckstyleMethodLength, ParameterNumber, ClassFanOutComplexity
IntelliJ inspections"Overly long method", "Class with too many methods", "Method with too many parameters"
Git historyFiles with the most commits and merge conflicts
Table 5 — Detection tools

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)

ForceCountermeasure
Adding to existing code is easiestBoy 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 fileCollective ownership; smaller files reduce conflicts
No quality gate on new codeSonar gate: no new methods above complexity threshold
Table 6 — Forces behind bloat

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.

JAVA
// 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

FeatureUse against bloaters
RecordsCheap parameter objects and value objects
Compact constructorsValidation inside parameter objects
StreamsReplace accumulating loops with pipelines
Sealed interfacesSplit variant behaviour out of large classes
IntelliJ: Extract Method (⌥⌘M), Extract Delegate, Introduce Parameter ObjectAutomated cures
SonarLint in IDEImmediate feedback on size and complexity
Table 7 — Java and tooling support

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

JAVA
// Before
double fee = feeCalculator.fee(order.getCountry(), order.getWeight(), order.isExpress());
// After
double fee = feeCalculator.fee(order);          // callee picks what it needs

Trade-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.

StepRefactoringResult
1Field-usage analysis (IntelliJ "Dependency Structure", manual matrix)5 clusters: profile, addresses, loyalty, preferences, GDPR export
2Characterisation tests for public methods used by controllersSafety net
3Extract Class LoyaltyAccount (fields + 18 methods)Service delegates
4Extract Class AddressBook, NotificationPreferencesTwo more collaborators
5Move GDPR export to PersonalDataExporterSeparate module later
6Inline delegating methods; controllers call new classes directlyService down to profile use cases
Table 8 — God-class decomposition
MetricBeforeAfter
Largest class1,850 lines420 lines
Merge conflicts in module per month~14~3
Median lines changed per ticket18070
Table 9 — Outcome

6.4 Worked example — measuring bloat in CI

XML
<!-- 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>
PolicyEffect
Baseline existing violationsBuild not blocked by legacy
Fail on new violationsBloat stops growing
Report trend per sprintVisible progress as legacy violations are refactored away
Table 10 — "Clean as you code" policy

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).

StageLargest methodParameters per extracted method
Original140 lines—
Extract Method directly40 lines6–8 (unreadable)
Method Object, then Extract18 lines0–1
Move Method into domain objects12 lines0–1
Table 11 — Choosing the right sequence

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

ConcernReality
Many small methodsJIT inlines; negligible cost
More objects (parameter objects)Short-lived; escape analysis often eliminates them
Large classes in SpringLarge beans with many dependencies slow startup and tests
Operational diagnosisSmall, named methods produce clearer stack traces
Table 12 — Performance view

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

Q1L1 · BasicConcept

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.

Q2L1 · BasicCode

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.

Q3L2 · IntermediateDesign

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.

Q4L2 · IntermediateCode

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.

Q5L3 · Senior EngineerConcept

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.

Q6L3 · Senior EngineerTricky

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.

Q7L4 · Technical ArchitectScenario

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.

Q8L5 · Solution ArchitectDesign

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.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.