Chapter 9: Refactoring Legacy Code
The introduction frames data-oriented refactoring as a way to improve ordinary legacy code incrementally by bringing its hidden data to the surface.
After this chapter you will be able to
- Hidden Data in Legacy Code. Explain why data-oriented work often begins by refactoring existing code rather than implementing explicitly data-oriented requirements.
- Shared cart entity boundaries. Explain how ShoppingCart and CartItem serve as the database model, application model, and front-end rendering model, creating boundary issues.
- Complicated scattered cart behavior. Describe why adding an item to the cart has become difficult and how its behavior is divided across the existing code.
- Problem-first refactoring. Explain why studying the existing code should come before adding services or redrawing object responsibilities, using the Cart example to show what premature restructuring can miss.
- Unclear entity invariants. Explain why the messy modeling burdens other code: it is hard to modify these objects safely when the code does not reveal what invariants must be preserved.
- Cart state mutated externally. Describe how code outside the Cart changes its internal state, sometimes through behavioral methods but more often by reaching directly into it, including from several layers down the call stack.
- Eroded encapsulation and invariants. Explain why growing mutable Entities tend to lose encapsulation and why relying on people to check invariants after mutation is fragile.
- Sequential coupling and encapsulation. Explain what sequential or temporal coupling is and why it violates encapsulation.
- Single-purpose methods and invariants. Explain how seemingly well-scoped methods can introduce sequential coupling when they leave an object inconsistent until another method runs.
- Partial Cart Item Construction. Explain why converting incoming items into CartItems leaves them partially constructed: the request lacks information needed to fill the entity’s fields.
- Late Seller ID Assignment. Trace how assigning sellerId after validation and processing have begun can let an invalid CartItem through and produce a duplicate in the customer’s cart.
- Preventing recurring code problems. Explain why a great refactor does more than fix existing problems: it sets new standards, starting with data, so the same problems are less likely to recur.
- Cart invariants from requirements. Explain how to turn action-oriented cart requirements into statements that must hold for every valid cart state, including the limit on desired quantity.
- Immutable cart state and uniqueness. Explain why immutable cart data must be valid when constructed and why a List or Set does not adequately express item uniqueness based on identifying attributes.
- Explicit presence and optionality. Explain why the refactored cart explicitly rejects nulls for required fields and makes genuine optionality visible.
- Data Types as Gatekeepers. Explain how a data type can establish a boundary at an arbitrary point in code by requiring callers to construct an instance before proceeding.
- Incremental ValidCart Boundary. Describe where the section proposes requiring ValidCart and how that boundary guides an incremental refactor.
- Limits of error-only validation. Explain why finding no errors in an input object does not necessarily mean a feature is ready to proceed. Describe how object-local validation can miss information the feature needs from elsewhere.
- Validation boundary as evidence. Describe validation as a preflight boundary whose output is a data type encoding what has been established. Explain how requiring that type makes necessary data loading happen before the rest of the work proceeds.
- Intermediate Cart lifecycle state. Explain why refreshing Cart data may create a state that cannot yet satisfy ValidCart invariants, and why that intermediate state should be represented separately rather than weakening those invariants.
- Map Transformation Utilities. Explain why the section moves Map-transforming code into a utility instead of repeating streams and collectors at each call site.
- Cart Logic as Set Operations. Describe how intersections and differences help express the cart requirements without framing them as loops, branches, or moving mutable items.
- Map Collision Decisions. Distinguish set-like operations on Maps from those on Sets, and explain the two collision choices described here.
- Controlled mutation for cart balancing. Explain why the cart-balancing logic can use loops and mutable collections instead of increasingly complicated set operations, while still behaving as a pure, deterministic function.
- Incremental legacy code boundary. Describe how the refactor can stop after introducing the new data model for one feature, while continuing to work with the legacy Entities.
- Timing of object boundaries. Explain why questions about object ownership and responsibility were deferred, and why it is reasonable to revisit them once domain data types protect invariants and boundaries control data flow.
- Incremental Data Oriented Refactoring. Explain why the section argues that legacy code can be improved gradually, starting with a good data type or representation rather than a wholesale rewrite.
- Incremental refactoring with data types. Explain how introducing a good data type can provide a starting boundary for refactoring legacy code, allowing its influence to grow through incremental changes.
What it builds on
- Invariants, Properties, State, and an upside-down capital A (chapter 7) · The idea of properties that hold for every possible state.
- Programming with immutable data (chapter 2) · The use of immutable data to avoid changing state.
- Separate how you get the data from what you do with it (chapter 5) · Separating how data is obtained from what is done with it.
- The algebraic properties of binary operations (chapter 7) · Binary operations and their properties
- Functions, Purity, and Determinism (chapter 6) · the distinction between mutation and a function’s externally observable purity and determinism
- Treat legacy Entities as Data Transfer Objects (chapter 6) · treating legacy Entities as data transfer objects
Section by section
Introduction
The introduction frames data-oriented refactoring as a way to improve ordinary legacy code incrementally by bringing its hidden data to the surface.
- Hidden Data in Legacy Code: Explain why data-oriented work often begins by refactoring existing code rather than implementing explicitly data-oriented requirements.
Why it matters: This explains why data orientation is useful even when you inherit code that was not designed for it. - Incremental Data-Oriented Refactoring: Explain why the introduction presents replacing objects with data as an incremental approach to refactoring.
Why it matters: The chapter’s approach makes improvement possible without a wholesale rewrite.
Key terms: data-oriented, refactoring, data, objects, data type, incremental
9.1 A messy starting point
The section introduces a legacy shopping-cart service whose growing feature complexity, shared entity models, and scattered behavior make it a difficult starting point for refactoring.
- Shared cart entity boundaries: Explain how ShoppingCart and CartItem serve as the database model, application model, and front-end rendering model, creating boundary issues.
Why it matters: This identifies a concrete problem the refactoring must address. - Complicated scattered cart behavior: Describe why adding an item to the cart has become difficult and how its behavior is divided across the existing code.
Why it matters: It explains why a seemingly simple cart action is hard to change safely.
Key terms: ShoppingCart, CartItem, Entity types, boundary issues, inventory checks, state management, upselling, Cart object, main controller
9.2 Analyzing common problems in code
The section argues that refactoring should begin by identifying problems in the existing code, rather than by rearranging architectural boundaries.
- Problem-first refactoring: Explain why studying the existing code should come before adding services or redrawing object responsibilities, using the Cart example to show what premature restructuring can miss.
Why it matters: It gives you a way to judge whether a proposed refactor addresses a real problem or just moves code around.
Key terms: responsibility boundaries, indirection, refactors
9.2.1 Messy data modeling
The section identifies poorly focused Cart and item models and explains why their unclear invariants make refactoring risky.
- Cart and item responsibilities: Describe how the existing Cart and its items lack cohesion: much of the Cart’s representation is unrelated to holding shopping items, while its items also act as inventory trackers.
Why it matters: Spotting mixed responsibilities helps explain why these models are difficult to work with. - Unclear entity invariants: Explain why the messy modeling burdens other code: it is hard to modify these objects safely when the code does not reveal what invariants must be preserved.
Why it matters: Before changing an entity, you need to be able to tell which conditions a change must preserve.
Key terms: Cart, Inventory Tracker, lack of cohesion, invariants, Entities
9.2.2 Uncontrolled mutation
This section identifies uncontrolled mutation in the legacy Cart, explains why it undermines encapsulation and invariants, and cautions against treating all mutation as the problem.
- Cart state mutated externally: Describe how code outside the Cart changes its internal state, sometimes through behavioral methods but more often by reaching directly into it, including from several layers down the call stack.
Why it matters: Spotting where state changes originate makes the Cart’s loss of control visible. - Eroded encapsulation and invariants: Explain why growing mutable Entities tend to lose encapsulation and why relying on people to check invariants after mutation is fragile.
Why it matters: This explains why scattered checks cannot reliably repair a lost boundary. - Mutation versus design problem: Distinguish uncontrolled mutation from mutation in general when describing what the refactoring needs to address.
Why it matters: It keeps the refactoring focused on the actual design failure rather than on eliminating mutation indiscriminately.
Key terms: Cart, uncontrolled mutation, behavioral methods, mutable Entities, encapsulation boundaries, invariants, mutable reference, mutable state, refactoring
9.2.3 Sequential coupling
This section explains how methods that must be called in a particular order undermine encapsulation and can leave an object in an inconsistent state.
- Sequential coupling and encapsulation: Explain what sequential or temporal coupling is and why it violates encapsulation.
Why it matters: Callers should not have to discover a hidden method order to use an object safely. - Single-purpose methods and invariants: Explain how seemingly well-scoped methods can introduce sequential coupling when they leave an object inconsistent until another method runs.
Why it matters: A tidy-looking method can still make an object unsafe between calls.
Key terms: sequential coupling, temporal coupling, encapsulation, single responsibility, invariants, atomic, updateMetadata, updateInventory
9.2.4 Hidden knowledge, partial construction, and shotgun validation
This section shows how partially constructed cart items, hidden assumptions, and validation that happens too early can combine to create a duplicate-item bug.
- Partial Cart Item Construction: Explain why converting incoming items into CartItems leaves them partially constructed: the request lacks information needed to fill the entity’s fields.
Why it matters: A CartItem that looks ready for processing may still be missing information the code relies on. - Late Seller ID Assignment: Trace how assigning sellerId after validation and processing have begun can let an invalid CartItem through and produce a duplicate in the customer’s cart.
Why it matters: The order of validation and assignment explains why individually reasonable methods can still permit a serious cart error. - Hidden Invariant Assumptions: Explain why this kind of bug can be hard to spot even when individual methods appear sound, and relate it to the section’s description of shotgun parsing.
Why it matters: Looking only at methods in isolation can miss failures caused by assumptions spread across a code path.
Key terms: partial construction, Entity, CartItem, sellerId, validation, invalid state, hidden knowledge, invariants, Shotgun Parsing
9.3 Fixing the problems
This section frames refactoring as a chance to prevent recurring problems by starting with data and setting better modeling standards.
- Preventing recurring code problems: Explain why a great refactor does more than fix existing problems: it sets new standards, starting with data, so the same problems are less likely to recur.
Why it matters: Better patterns help prevent a codebase from drifting back toward the problems you just fixed.
Key terms: refactor, data, illegal states
9.3.1 Work backwards from invariants
The section works backward from cart requirements to invariants, then uses those invariants to guide a practical refactor of the cart’s data model.
- Cart invariants from requirements: Explain how to turn action-oriented cart requirements into statements that must hold for every valid cart state, including the limit on desired quantity.
Why it matters: State invariants give the new model a clearer target than a list of actions to reproduce. - Immutable cart state and uniqueness: Explain why immutable cart data must be valid when constructed and why a List or Set does not adequately express item uniqueness based on identifying attributes.
Why it matters: Choosing a representation that expresses the rule prevents the refactor from merely hiding old problems behind constructor checks. - Pragmatic first refactor tradeoffs: Justify retaining the cart item’s inventory counts in the first refactor despite their awkward coupling, and distinguish internal modeling from presentation.
Why it matters: A workable refactor can protect correctness without demanding every design improvement at once. - Explicit presence and optionality: Explain why the refactored cart explicitly rejects nulls for required fields and makes genuine optionality visible.
Why it matters: Explicit presence rules help old habits stop producing carts that look usable but violate the model.
Key terms: invariants, for all states, Desired ≤ Available, Active cart, immutable data, defensive copies, List, Set, Maps, uniqueness
9.3.2 Draw boundaries with data
This section shows how a data type can create a proof-requiring boundary inside legacy code and provide a starting point for incremental refactoring.
- Data Types as Gatekeepers: Explain how a data type can establish a boundary at an arbitrary point in code by requiring callers to construct an instance before proceeding.
Why it matters: It lets you protect code according to the data it requires, even when existing object boundaries are awkward. - Incremental ValidCart Boundary: Describe where the section proposes requiring ValidCart and how that boundary guides an incremental refactor.
Why it matters: A small, well-placed data requirement gives you a way to improve messy code without rewriting it all at once.
Key terms: data types, boundaries, gate keeper, proof, Curry-Howard Correspondence, ValidCart, boundary, incrementally, invariants
9.3.3 Make validation about evidence rather than errors
The section reframes validation as a boundary that produces data proving a feature’s preconditions are met, including when the data represents an intermediate state.
- Limits of error-only validation: Explain why finding no errors in an input object does not necessarily mean a feature is ready to proceed. Describe how object-local validation can miss information the feature needs from elsewhere.
Why it matters: An error-free request can still leave important work and knowledge scattered through the code. - Validation boundary as evidence: Describe validation as a preflight boundary whose output is a data type encoding what has been established. Explain how requiring that type makes necessary data loading happen before the rest of the work proceeds.
Why it matters: A data type that can be constructed only after preflight work makes the boundary meaningful to code that follows it. - Intermediate Cart lifecycle state: Explain why refreshing Cart data may create a state that cannot yet satisfy ValidCart invariants, and why that intermediate state should be represented separately rather than weakening those invariants.
Why it matters: Naming the intermediate state preserves the final Cart’s invariants without hiding a necessary step in its lifecycle.
Key terms: error-centric view, preconditions, shotgun parsing, validation boundary, evidence, preflight checks, ValidAddItemsRequest, Item, Cart, ValidCart
9.3.4 Write utilities that make data-oriented programs more expressive
This section shows how small Map utilities make immutable cart logic easier to express, reason about, and refactor.
- Map Transformation Utilities: Explain why the section moves Map-transforming code into a utility instead of repeating streams and collectors at each call site.
Why it matters: The refactored code can say what it does without repeatedly spelling out how to do it. - Cart Logic as Set Operations: Describe how intersections and differences help express the cart requirements without framing them as loops, branches, or moving mutable items.
Why it matters: Set-like questions expose the shape of the requirements without relying on mutation-oriented control flow. - Map Collision Decisions: Distinguish set-like operations on Maps from those on Sets, and explain the two collision choices described here.
Why it matters: Map utilities need an explicit value rule, not just a rule for which keys overlap. - Measured Performance Tradeoffs: Explain why the section recommends measuring performance before rejecting immutable copies, while allowing mutation when measurement warrants it.
Why it matters: Measurement lets you keep expressive immutable code unless its cost actually matters.
Key terms: Map, utility function, streams and collectors, intersection, difference, set-like operations, Active and Saved cart items, collision, BinaryOperator, right biased
9.3.5 Keep mutation where useful, but use it to build data
This section shows how controlled local mutation can simplify a data-oriented refactor and how a new data model can coexist with legacy code during incremental migration.
- Controlled mutation for cart balancing: Explain why the cart-balancing logic can use loops and mutable collections instead of increasingly complicated set operations, while still behaving as a pure, deterministic function.
Why it matters: Data-oriented code need not reject a simpler algorithm just because it uses mutation internally. - Incremental legacy code boundary: Describe how the refactor can stop after introducing the new data model for one feature, while continuing to work with the legacy Entities.
Why it matters: This boundary lets a team improve one feature without first replacing the whole legacy codebase.
Key terms: mutation, mutable collections, pure, deterministic function, immutable data, cart, data model, Entities, Data transfer Object (DTO), serialize, incremental improvements
9.3.6 Now consider object boundaries
The section explains why object ownership and service boundaries are best reconsidered after the refactoring has established sound data types and data-flow boundaries.
- Timing of object boundaries: Explain why questions about object ownership and responsibility were deferred, and why it is reasonable to revisit them once domain data types protect invariants and boundaries control data flow.
Why it matters: It helps you distinguish a structural improvement from a change that only relocates flawed code. - Data types as seams: Describe why the section presents options such as a Cart service or Store Façade as easy to consider at this stage rather than as required designs.
Why it matters: Good data boundaries leave room to choose an object arrangement without redoing the core refactoring.
Key terms: ownership, responsibility, invariants, boundaries, data flow, Cart, Store Façade, data-oriented code, seam
9.4 Some encouragement on refactoring legacy code
The section encourages incremental data-oriented refactoring of legacy code rather than accepting decline or waiting for a rewrite.
- Legacy Code Downward Spiral: Explain how postponing cleanup can make poor code quality seem normal and even justify further decline.
Why it matters: Recognizing this pattern helps explain why a difficult codebase need not stay that way. - Incremental Data Oriented Refactoring: Explain why the section argues that legacy code can be improved gradually, starting with a good data type or representation rather than a wholesale rewrite.
Why it matters: The section offers a practical alternative to waiting for permission to replace the whole system.
Key terms: refactoring, downward spiral, existing patterns, data type, data-orientation, representation
9.5 Wrapping up
The section closes by presenting data types as a way to refactor code incrementally by reshaping its boundaries.
- Incremental refactoring with data types: Explain how introducing a good data type can provide a starting boundary for refactoring legacy code, allowing its influence to grow through incremental changes.
Why it matters: You can begin improving legacy code at one boundary rather than changing everything at once.
Key terms: data type, boundaries, Curry-Howard Correspondence
9.6 Summary
Where this is used later
- The Object Oriented Thought Process (chapter 10) · The problem of operating on partial data.
- A way of thinking about software architecture (chapter 10) · Extends the discussion of boundaries to application architecture.
Concepts explained in this chapter
- invariantAn invariant is a condition that must remain true across the valid states of a data structure or computation.
- validationValidation is the process of checking data and system conditions against the preconditions required for safe continuation.
- mutationMutation is the modification of an existing program value or state in place.
- missing valueA special Java reference value indicating the absence of an object rather than an instance of the referenced type.
- data typeA data type is a classification of data that determines its representation, permitted values, and valid operations.
- evidenceEvidence is information that demonstrates that a required data condition or capability has been established.
- refactoringRefactoring is the restructuring of existing software without changing its externally observable behavior.
- Curry-Howard correspondenceThe Curry-Howard correspondence is a relationship between formal logic and computation in which propositions correspond to types and proofs correspond to values or programs satisfying them.
- functionA computation that maps input values to an output value or values without requiring mutation of the input values.
- right-biased map operationA right-biased map operation resolves duplicate keys by selecting the value from the right-hand map.
- set operationA set operation is an operation that combines or compares collections according to set membership, such as intersection, union, or difference.
- defensive copyA defensive copy is an independently created duplicate of mutable data that prevents external mutation from changing the original representation.
- illegal stateAn illegal state is a program state that violates the validity constraints imposed by its data model or domain rules.
- hidden knowledgeHidden knowledge is information about required behaviors, assumptions, or validity conditions that exists in code but is not stated in requirements or exposed at an interaction boundary.
- shotgun parsingShotgun parsing is a parsing and validation style in which interpretation and checks are scattered across code paths, allowing assumptions and incomplete data to escape their intended boundaries.
- assertionAn assertion is an executable check that a specified condition holds for a value, state, or computation.
- data-oriented programmingData-oriented programming is a programming approach that organizes software around explicit data representations and operations on those representations.
- data transfer objectA data transfer object is a data-carrying structure used to exchange information between software components without encapsulating domain behavior.
- dataData is information represented independently of the behaviors that operate on it.
- constructor methodA constructor is a class member that initializes a newly created object and establishes its initial state.
- mutable referenceA mutable reference is a reference that provides access to an object whose state can be changed.
- algebraic lawAn algebraic property is a characteristic describing how an operation behaves under operand order, grouping, and relationships between inputs and outputs.
- optionalityThe property of domain information that may be present or absent and whose absence has explicit meaning.
- setA set is a collection that represents distinct elements without treating duplicate occurrences as separate members.
- data modelingData modeling is the design process of identifying domain information, its meaning, and its representation.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
