- 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. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally — When to Refactor
- 4A. Deep Dive — Making the Economic Case
- 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
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.

| Goal | Mechanism | Observable result |
|---|---|---|
| Reduce complexity | Smaller units, clearer conditionals, less duplication | Code easier to read and reason about |
| Improve maintainability | Names, cohesion, encapsulation, tests | Fewer defects, faster onboarding, cheaper fixes |
| Enable change | Seams, decoupling, abstractions where variation exists | New features touch fewer places |
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.

// 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;
}// 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 reducer | Example above |
|---|---|
| Guard clauses | Early return for null/empty order |
| Extract Method | itemCost, primeWaiver |
| Named constants | FRAGILE_FEE, HEAVY_KG |
| Replace loop with pipeline | stream().map().reduce() |
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 factor | Refactoring contribution |
|---|---|
| Analysability | Intention-revealing names, small methods, no dead code |
| Modifiability | High cohesion, low coupling, no duplication |
| Testability | Pure functions extracted, dependencies injectable |
| Modularity | Clear package/module boundaries (Spring Modulith, ArchUnit) |
| Reusability | Value objects and policies usable in several places |
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.
// 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.
4How It Works Internally — When to Refactor

| Occasion | Description | Size |
|---|---|---|
| Preparatory | Before a feature, reshape the code so the feature fits | Minutes to hours |
| Comprehension | While reading code, rename and extract to capture understanding | Minutes |
| Litter-pickup (Boy Scout rule) | Leave code a little better than you found it | Minutes |
| Rule of three | Third duplication → extract the abstraction | Minutes to hours |
| Planned | Known structural problem tracked as a small backlog item | Hours to days |
| Long-term | Large restructuring done incrementally with a target | Weeks, in small steps |
When not to refactor:
| Situation | Reason |
|---|---|
| Code you never need to change or understand | No payoff |
| Code that will be replaced soon (confirmed) | Investment lost |
| No tests and no way to add them cheaply | Risk too high — first add characterisation tests (Chapter 4) |
| In the middle of a production incident | Fix first, refactor later |
| Rewriting is genuinely cheaper (rare) | Small, isolated, well-specified component |
4ADeep Dive — Making the Economic Case
Stakeholders rarely buy "cleaner code". They buy speed, predictability and quality. Frame refactoring in those terms.
| Stakeholder concern | Refactoring argument | Evidence to show |
|---|---|---|
| "Why are features slow?" | Code in area X is tangled; each change touches many files | Change size and lead time per feature in area X |
| "Why so many bugs?" | Duplicated logic diverges; complex methods hide defects | Defect density vs complexity hotspots |
| "Can we add provider Y quickly?" | Preparatory refactoring makes it a small change | Estimate with and without refactoring |
| "Onboarding takes months" | Unclear structure; names don't reflect domain | Time for new joiners to first meaningful change |
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.
# 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| File | Changes/year | Cognitive complexity | Priority |
|---|---|---|---|
OrderPricingService.java | 142 | 310 | Refactor now |
InvoicePdfRenderer.java | 8 | 280 | Leave (rarely changed) |
CheckoutController.java | 96 | 40 | Fine |
TaxRules.java | 77 | 190 | Refactor next |
5APIs / Features / Syntax
| Tool | Use in making refactoring decisions |
|---|---|
| SonarQube / SonarLint | Cognitive and cyclomatic complexity, duplication, issues |
| CodeScene / git log scripts | Hotspots, change coupling, knowledge distribution |
| IntelliJ inspections | Local smells: long methods, duplicated code, unused code |
| ArchUnit / Spring Modulith | Detect boundary violations that make change expensive |
| JaCoCo | Test coverage to judge refactoring risk |
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:
| Quarter | Product types | Avg. files changed per new type | Avg. lead time |
|---|---|---|---|
| Q1 Y1 | 3 | 4 | 3 days |
| Q3 Y1 | 6 | 9 | 6 days |
| Q1 Y2 | 9 | 15 | 11 days |
| Q3 Y2 (after refactoring to strategies) | 11 | 2 | 1.5 days |
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
| Task | Without preparatory refactoring | With preparatory refactoring |
|---|---|---|
| Add second payment provider | Insert conditionals in 6 places, duplicate error handling, test all paths: ~5 days | Extract 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 risk | High (scattered changes) | Low (isolated adapter) |
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 refactoring | After refactoring |
|---|---|
Logic inside controllers and @Transactional services; tests need Spring context and DB | Pure 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 setup | Small methods and objects; each tested with focused cases |
| Test suite: 12 minutes, flaky | Test suite: 90 seconds for unit tests; integration tests reserved for wiring |
// 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
| Aspect | Consideration |
|---|---|
| Runtime performance | Usually unaffected; refactored code is easier to optimise |
| Deployment frequency | Small refactorings fit continuous delivery |
| Operational risk | Reduced over time as code becomes clearer and better tested |
| Incident response | Clear code shortens diagnosis time |
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
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.
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.
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.
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.
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.
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.
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.
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.