Refactoring improves a design without merely rearranging its problems. Collapsing fields or Boolean flags can make code DRYer while leaving contextual meaning, nullable values, and illegal states intact. A useful change starts by identifying the flaw, then makes the domain model express the rules that previously required defensive checks. section 4.1.6 section 9.2 section 9.3
In a legacy e-commerce cart, years of features leave entity classes responsible for persistence, application behavior, rendering, inventory concerns, and mutable cart state. Rather than begin with a new service layer or a design pattern, study the concrete failures first. Moving code behind indirection can hide a troubled Cart without correcting it. section 9.1 section 9.2
A data-oriented refactoring proceeds by making evidence and boundaries explicit:
- Enumerate existing problems and articulate the invariant being violated; work backward from requirements rather than from preferred architecture. section 9.2 section 9.6
- Replace representations that permit bad combinations with data types that make illegal states impossible or reject them at construction. section 4.1.6 section 9.6
- Separate data acquisition from business decisions by passing fetched data into core methods, quarantining database and network side effects. section 5.5.2
- Use algebraic laws to explore equivalent domain-model shapes, preserving invariants while factoring duplicated information. section 4.6.4
Factoring a status model safely
A Status record may combine a state enum with actionedBy, actionedOn, and rationale fields. This removes duplicated fields, but a NOT_STARTED status can still carry completion data and callers must repeatedly guard against nulls. Model the distinct alternatives directly instead of relying on contextual fields and validation branches. section 4.1.6
Figure 4.19 Applying the distributive law over Sum and Product types to factor out duplication

The distributive-law transformation visualizes how duplicated fields can be factored from a sum of product types without changing the represented information. section 4.6.4
Refactoring need not eliminate objects or mutation. Control mutation where it causes trouble, use data to establish boundaries, and return to ordinary object-oriented responsibility questions after the original problems are understood and addressed. section 9.0 section 9.6




























