From "Refactoring"
🎧 Listen to Summary
Free 10-min PreviewMove Field
Key Insight
Program strength is fundamentally rooted in well-designed data structures, as robust structures lead to simpler, clearer behavior code, while poor structures cause complex, hard-to-understand code. Initial data structure analysis can be challenging, and even with experience and techniques like domain-driven design, mistakes in the initial design are common. Understanding of the problem domain evolves during programming, making a design decision that was initially correct potentially wrong later. It is crucial to change incorrect data structures promptly, as their flaws can obscure program logic and complicate future development.
Data fields are often moved because they are consistently passed together with another record to functions, indicating they should be grouped within a single record to clarify their relationship. Similarly, if a change in one record consistently triggers a change in a field within another, or if the same field requires updates across multiple structures, it suggests the field is misplaced and should be moved to a location where it only needs one update. This refactoring is frequently part of a broader set of changes. After moving a field, its users may benefit from accessing it through the target object rather than the original source, necessitating further refactorings.
The mechanics for moving a field typically assume an object-oriented context where data is encapsulated behind accessor methods, making the refactoring easier. First, the source field must be encapsulated, and tests are run. Next, a new field and its accessors are created in the target context, followed by static checks. A reference from the source object to the target object must exist; if not, one may need to be created temporarily or permanently. Accessors in the source are then adjusted to use the new target field. If the target field is shared, a setter can be updated to modify both source and target fields, and an assertion (302) can be introduced to detect inconsistencies before finalizing the change. Finally, the source field is removed after successful testing. An example shows moving 'discountRate' from 'Customer' to 'CustomerContract', involving encapsulating the field, creating it on the target, and adjusting accessors. Another example involves moving 'interestRate' from 'Account' to 'AccountType', emphasizing the need to verify that all accounts of the same type already share the same interest rate to avoid introducing observable behavior changes, potentially using 'Introduce Assertion' (302) for verification.
📚 Continue Your Learning Journey — No Payment Required
Access the complete Refactoring summary with audio narration, key takeaways, and actionable insights from Martin Fowler, Kent Beck.