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

Why Refactor?

Reduce complexity, improve maintainability, enable change

10 min readStage 2 · Frameworks & design8 interview questions
Chapter
Chapter 1 — Refactoring Fundamentals
Prerequisites
Topic 1.1
You will be able to
Explain the economic case for refactoring, show how it reduces complexity and improves maintainability, use preparatory refactoring to enable change, recognise the right moments to refactor (and when not to), and communicate refactoring value to non-technical stakeholders
Covers
Reduce complexity; Improve maintainability; Enable change
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — When to Refactor
  5. 4A. Deep Dive — Making the Economic Case
  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

We refactor to keep the cost of change low. Fowler's Design Stamina Hypothesis states that investing in good internal design lets a team keep delivering features at a steady pace, while neglecting design makes each feature progressively slower — and that the investment pays off within weeks, not years.

Cost of change over time
Figure 1 — Cost of change over time
GoalMechanismObservable result
Reduce complexitySmaller units, clearer conditionals, less duplicationCode easier to read and reason about
Improve maintainabilityNames, cohesion, encapsulation, testsFewer defects, faster onboarding, cheaper fixes
Enable changeSeams, decoupling, abstractions where variation existsNew features touch fewer places
Table 1 — The three goals of refactoring

2Why It Exists

Software entropy is inevitable: requirements change, understanding deepens, shortcuts accumulate. Lehman's laws of software evolution observe that systems in use must change continuously, and that their complexity increases unless work is done to reduce it. Without refactoring, code accumulates accidental complexity — structure that reflects history rather than the problem — and teams slow down, estimates grow and defects multiply. Refactoring is the continuous "work done to reduce it".

3Core Concepts

3.1 Reduce complexity

Complexity is what makes code hard to understand: many paths, deep nesting, mixed abstraction levels, hidden dependencies.

Complexity before and after refactoring
Figure 2 — Complexity before and after refactoring
JAVA
// Before: cognitive complexity ~22
public BigDecimal shippingCost(Order o) {
    BigDecimal cost = BigDecimal.ZERO;
    if (o != null) {
        if (o.getItems() != null && !o.getItems().isEmpty()) {
            for (Item i : o.getItems()) {
                if (i.isFragile()) {
                    cost = cost.add(new BigDecimal("50"));
                } else if (i.getWeightKg() > 20) {
                    if (o.getCountry().equals("IN"))
                        cost = cost.add(new BigDecimal("120"));
                    else
                        cost = cost.add(new BigDecimal("400"));
                } else {
                    cost = cost.add(new BigDecimal("30"));
                }
            }
            if (o.isPrime() && cost.compareTo(new BigDecimal("500")) < 0)
                cost = BigDecimal.ZERO;
        }
    }
    return cost;
}
JAVA
// After: guard clauses, extracted rules, each method trivial
public BigDecimal shippingCost(Order order) {
    if (order == null || order.getItems().isEmpty()) return BigDecimal.ZERO;
    BigDecimal cost = order.getItems().stream()
            .map(item -> itemCost(item, order.getCountry()))
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    return primeWaiver(order, cost);
}
 
private BigDecimal itemCost(Item item, String country) {
    if (item.isFragile()) return FRAGILE_FEE;
    if (item.getWeightKg() > HEAVY_KG) {
        return "IN".equals(country) ? HEAVY_DOMESTIC : HEAVY_INTERNATIONAL;
    }
    return STANDARD_FEE;
}
 
private BigDecimal primeWaiver(Order order, BigDecimal cost) {
    boolean waived = order.isPrime() && cost.compareTo(PRIME_FREE_LIMIT) < 0;
    return waived ? BigDecimal.ZERO : cost;
}
Complexity reducerExample above
Guard clausesEarly return for null/empty order
Extract MethoditemCost, primeWaiver
Named constantsFRAGILE_FEE, HEAVY_KG
Replace loop with pipelinestream().map().reduce()
Table 2 — Techniques used

Complexity is measured by cyclomatic complexity (number of independent paths) and cognitive complexity (SonarSource's measure of how hard code is to understand, penalising nesting). Chapter 6 covers both.

3.2 Improve maintainability

Maintainability is the ease with which code can be understood, corrected, adapted and extended (ISO/IEC 25010 sub-characteristics: modularity, reusability, analysability, modifiability, testability).

Maintainability factorRefactoring contribution
AnalysabilityIntention-revealing names, small methods, no dead code
ModifiabilityHigh cohesion, low coupling, no duplication
TestabilityPure functions extracted, dependencies injectable
ModularityClear package/module boundaries (Spring Modulith, ArchUnit)
ReusabilityValue objects and policies usable in several places
Table 3 — Maintainability and refactoring

Maintainability pays off most for code that is read and changed often. A team reads code far more often than it writes it; each minute saved understanding a class is saved again and again.

3.3 Enable change

The most powerful reason to refactor is to make the next change easy — preparatory refactoring.

JAVA
// Feature request: support a second payment provider.
// Before: provider calls embedded in the service
// → the feature would add if/else everywhere
public class CheckoutService {
    public Receipt pay(Order o) {
        // hard-wired
        var resp = stripeClient.charge(o.total().cents(), o.currency(), o.token());
        if (!resp.success()) throw new PaymentFailed(resp.error());
        return new Receipt(resp.id());
    }
}
 
// Preparatory refactoring (behaviour unchanged): extract an interface and an adapter
public interface PaymentGateway { Receipt charge(Money amount, PaymentToken token); }
 
class StripePaymentGateway implements PaymentGateway {
    public Receipt charge(Money amount, PaymentToken token) {
        var resp = stripeClient.charge(amount.cents(), amount.currency(), token.value());
        if (!resp.success()) throw new PaymentFailed(resp.error());
        return new Receipt(resp.id());
    }
}
 
public class CheckoutService {
    private final PaymentGateway gateway;
    public Receipt pay(Order o) { return gateway.charge(o.total(), o.token()); }
}
// The feature is now "add RazorpayPaymentGateway" — no change to CheckoutService.
Why refactor — three goals
Figure 3 — Why refactor — three goals

4How It Works Internally — When to Refactor

When to refactor
Figure 4 — When to refactor
OccasionDescriptionSize
PreparatoryBefore a feature, reshape the code so the feature fitsMinutes to hours
ComprehensionWhile reading code, rename and extract to capture understandingMinutes
Litter-pickup (Boy Scout rule)Leave code a little better than you found itMinutes
Rule of threeThird duplication → extract the abstractionMinutes to hours
PlannedKnown structural problem tracked as a small backlog itemHours to days
Long-termLarge restructuring done incrementally with a targetWeeks, in small steps
Table 4 — Refactoring occasions (Fowler)

When not to refactor:

SituationReason
Code you never need to change or understandNo payoff
Code that will be replaced soon (confirmed)Investment lost
No tests and no way to add them cheaplyRisk too high — first add characterisation tests (Chapter 4)
In the middle of a production incidentFix first, refactor later
Rewriting is genuinely cheaper (rare)Small, isolated, well-specified component
Table 5 — When not to refactor

4ADeep Dive — Making the Economic Case

Stakeholders rarely buy "cleaner code". They buy speed, predictability and quality. Frame refactoring in those terms.

Stakeholder concernRefactoring argumentEvidence to show
"Why are features slow?"Code in area X is tangled; each change touches many filesChange size and lead time per feature in area X
"Why so many bugs?"Duplicated logic diverges; complex methods hide defectsDefect density vs complexity hotspots
"Can we add provider Y quickly?"Preparatory refactoring makes it a small changeEstimate with and without refactoring
"Onboarding takes months"Unclear structure; names don't reflect domainTime for new joiners to first meaningful change
Table 6 — Framing refactoring for stakeholders

Hotspot analysis (Tornhill, Your Code as a Crime Scene): combine change frequency from git with complexity. Files that are both complex and frequently changed are where refactoring pays most; complex files that never change can be left alone.

BASH
# change frequency per file over the last year
git log --since=1.year --name-only --pretty=format: -- '*.java' \
  | sort | uniq -c | sort -rn | head -20
FileChanges/yearCognitive complexityPriority
OrderPricingService.java142310Refactor now
InvoicePdfRenderer.java8280Leave (rarely changed)
CheckoutController.java9640Fine
TaxRules.java77190Refactor next
Table 7 — Hotspot prioritisation

5APIs / Features / Syntax

ToolUse in making refactoring decisions
SonarQube / SonarLintCognitive and cyclomatic complexity, duplication, issues
CodeScene / git log scriptsHotspots, change coupling, knowledge distribution
IntelliJ inspectionsLocal smells: long methods, duplicated code, unused code
ArchUnit / Spring ModulithDetect boundary violations that make change expensive
JaCoCoTest coverage to judge refactoring risk
Table 8 — Analysis tools

6Practical Examples

6.1 Refactoring in estimates

Teams include preparatory refactoring in feature estimates ("adding provider Y: 2 days refactoring, 1 day feature") rather than requesting separate "refactoring sprints" that stakeholders see as lost time.

6.2 Boy Scout rule in reviews

Reviewers welcome small, separate refactoring commits accompanying features: a rename, an extracted method, a removed dead branch — each cheap, each compounding over time.

6.3 Worked example — the cost of not refactoring

A team tracked lead time for "add a new product type" requests in a pricing module over two years:

QuarterProduct typesAvg. files changed per new typeAvg. lead time
Q1 Y1343 days
Q3 Y1696 days
Q1 Y291511 days
Q3 Y2 (after refactoring to strategies)1121.5 days
Table 9 — Lead time before and after refactoring

The refactoring (Replace Conditional with Polymorphism across pricing, tax and display rules) took about 8 developer-days in small steps over three weeks, and paid for itself after the second new product type.

6.4 Worked example — preparatory refactoring estimate

TaskWithout preparatory refactoringWith preparatory refactoring
Add second payment providerInsert conditionals in 6 places, duplicate error handling, test all paths: ~5 daysExtract PaymentGateway (1 day), add adapter (1 day), test (0.5 day): ~2.5 days
Third provider next quarter~5 days again, higher risk~1 day
Defect riskHigh (scattered changes)Low (isolated adapter)
Table 10 — Comparing approaches

The preparatory approach is faster even for the first feature, because the refactoring removes the need to understand and modify scattered code.

6.5 Worked example — communicating a refactoring proposal

> Proposal: Refactor OrderPricingService (top hotspot: 142 changes/year, cognitive complexity 310). > Problem: Pricing changes take 6–11 days; 40% of pricing bugs originate here. > Plan: 3 weeks of incremental refactoring alongside feature work: characterisation tests → extract policies → strategies per product type. > Expected outcome: New product types in ~2 days; complexity per method < 15; pricing defects halved. > Risk control: No behaviour changes; characterisation tests; small daily merges; feature flags not needed. > Measure: Lead time for pricing tickets and defect count over the next two quarters.

A proposal like this — problem, plan, expected outcome, risk control, measurement — is how architects obtain support for larger refactorings.

6.6 Refactoring and the testing pyramid

Refactoring also improves testability, which in turn makes further refactoring cheaper — a virtuous circle.

Before refactoringAfter refactoring
Logic inside controllers and @Transactional services; tests need Spring context and DBPure policy classes and value objects; unit tests in milliseconds
Static calls to LocalDate.now(), new RestTemplate()Injected Clock, gateways as interfaces → deterministic tests
One 400-line method; test cases need complex setupSmall methods and objects; each tested with focused cases
Test suite: 12 minutes, flakyTest suite: 90 seconds for unit tests; integration tests reserved for wiring
Table 11 — Testability gains from refactoring
JAVA
// Before: untestable time dependency
boolean isExpired(Subscription s) { return s.endDate().isBefore(LocalDate.now()); }
 
// After: inject Clock (behaviour unchanged in production with Clock.systemDefaultZone())
boolean isExpired(Subscription s, Clock clock) {
    return s.endDate().isBefore(LocalDate.now(clock));
}
 
@Test
void expiredAfterEndDate() {
    Clock fixed = Clock.fixed(Instant.parse("2026-10-01T00:00:00Z"), ZoneOffset.UTC);
    assertThat(policy.isExpired(subscriptionEnding("2026-09-30"), fixed)).isTrue();
}

Fast, deterministic tests are the safety net of Topic 1.3; refactoring for testability is often the first refactoring in a legacy area (Chapter 4).

7Common Problems & Mistakes

  • Refactoring for aesthetics without a link to upcoming work.
  • Asking permission for everyday refactoring (it belongs in every task).
  • Refactoring cold code instead of hotspots.
  • Refactoring sprints detached from features — hard to justify, easily cancelled.
  • Gold-plating — endless restructuring without delivering.
  • No evidence of benefit — stakeholders lose trust.

8Performance & Production Considerations

AspectConsideration
Runtime performanceUsually unaffected; refactored code is easier to optimise
Deployment frequencySmall refactorings fit continuous delivery
Operational riskReduced over time as code becomes clearer and better tested
Incident responseClear code shortens diagnosis time
Table 12 — Production view

Because refactoring is meant to change no behaviour, its main production risk is an unintended behaviour change slipping through. Keep each step small and deploy frequently, so a regression is easy to locate and roll back. Behaviour-preserving does not always mean performance-preserving: replacing a loop with a stream, adding a query inside a newly extracted method or changing JPA fetching can alter latency, so compare key metrics such as p99 latency, query count and error rate before and after each release. For risky areas, run the old and new code paths side by side and compare their outputs, or route a small share of traffic through the new path behind a feature flag before switching over completely.

9Architecture & Design Considerations

  • Use hotspot analysis to direct refactoring where change and complexity meet.
  • Build refactoring into estimates and definition of done.
  • Use preparatory refactoring to realise architectural decisions incrementally.
  • Track delivery metrics per area to show the effect of design investment.

10Interview Questions & Answers

Q1L1 · BasicConcept

Why do we refactor?

We refactor to keep the cost of change low. Refactoring improves the internal structure of code without changing its observable behaviour, and its justification is economic, not aesthetic. It reduces complexity, through smaller methods, clearer conditionals and less duplication, so code is easier to reason about. It improves maintainability through better names, cohesion and testability, which means fewer defects and faster onboarding. Most importantly, it enables change: reshaping code so the next feature touches one place instead of six. Lehman's laws say complexity grows unless work is done to reduce it; refactoring is that work. The right refactoring is one that makes current or upcoming work cheaper, faster or safer.

Q2L1 · BasicConcept

What is preparatory refactoring?

Preparatory refactoring means restructuring the code, without changing behaviour, so that an upcoming feature becomes easy to add, and then adding the feature. Kent Beck's summary is: make the change easy, then make the easy change. For example, before supporting a second payment provider, extract a PaymentGateway interface and move the existing Stripe calls into a StripePaymentGateway adapter, keeping all tests green. The new feature is then just another adapter, with no conditionals scattered through CheckoutService. It is usually faster even for the first feature, because you avoid modifying tangled code, and it is the easiest refactoring to justify, because it sits inside the feature's estimate.

Q3L2 · IntermediateConcept

What is the Design Stamina Hypothesis?

Martin Fowler's Design Stamina Hypothesis says that investing in good internal design lets a team keep delivering features at a steady pace, while neglecting design makes each feature progressively slower. Plotted over time, the no-design curve starts faster but flattens, and the good-design curve overtakes it at the design payoff line. Fowler argues that line arrives within weeks, not years, so the claim that there is no time for design rarely holds even in the short term. It is called a hypothesis because it is hard to measure objectively, but lead time and files changed per feature in a decaying module usually illustrate it clearly.

Q4L2 · IntermediateTrade-off

When should you not refactor?

Do not refactor when it cannot pay off or the risk outweighs the benefit. Code that works and that nobody needs to change or understand earns no return, however ugly it is. Code confirmed to be replaced soon is not worth the investment. Without tests, and with no cheap way to add them, refactoring is risky; first add characterisation tests that pin down current behaviour, then refactor. During a production incident, fix first and refactor later. Occasionally, rewriting a small, isolated, well-specified component is genuinely cheaper. Also avoid slipping risky restructuring into a change just before a release, and avoid open-ended restructuring with no link to upcoming work.

Q5L3 · Senior EngineerConcept

What is the Boy Scout rule?

The Boy Scout rule, popularised by Robert C. Martin, says: leave the code a little cleaner than you found it. Whenever you touch code for a feature or a fix, make one or two small improvements, such as renaming a misleading variable, extracting a method, replacing a magic number with a named constant or deleting a dead branch. Each improvement takes minutes and carries little risk, but because frequently changed code is touched often, the effect compounds exactly where it matters most. Keep these improvements in separate commits from behaviour changes so reviews stay easy. It is the continuous counterpart to planned refactoring, and needs nobody's permission.

Q6L3 · Senior EngineerScenario

How do you find where refactoring pays most?

Use hotspot analysis, from Adam Tornhill's Your Code as a Crime Scene: combine change frequency with complexity. Change frequency comes from git history, for example counting commits per file over the last year with git log --name-only; complexity comes from SonarQube's cognitive complexity or a similar metric. Files that are both complex and frequently changed are where developers pay the most interest, so refactor them first. A complex file that changed twice last year can be left alone. Refine the ranking with defect density, lead time per area and change coupling, meaning files that always change together. CodeScene automates this, but a shell script and a spreadsheet are enough to start.

Q7L4 · Technical ArchitectScenario

How do you justify refactoring to stakeholders?

Stakeholders do not buy cleaner code; they buy speed, predictability and quality, so I frame refactoring in those terms. I show evidence for the specific area: lead time for recent changes, files touched per feature, the share of defects originating there and its hotspot ranking. I link the work to upcoming roadmap items, ideally with two estimates, for example five days for the next payment provider without refactoring and two and a half with it. The proposal states the problem, an incremental plan alongside feature work, expected outcomes, risk controls such as characterisation tests and small daily merges, and the metrics we will report afterwards, which builds credibility.

Q8L5 · Solution ArchitectDesign

How do you ensure refactoring happens across an organisation?

Make refactoring part of normal delivery rather than a special activity. Teams include preparatory refactoring in feature estimates and the definition of done, and reviewers welcome small refactoring commits, so nobody needs permission for everyday cleanup. Give teams analysis tooling, such as SonarQube, hotspot reports and ArchUnit or Spring Modulith boundary checks in the pipeline, plus delivery metrics per area so they can see where design debt hurts. For larger structural problems, keep a visible, prioritised list tied to the architectural direction and deliver it incrementally alongside features. Report outcomes such as reduced lead time to leadership, and coach and pair with teams, because skills matter as much as policy.

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.