Cover of Refactoring by Martin Fowler, Kent Beck - Business and Economics Book

From "Refactoring"

Author: Martin Fowler, Kent Beck
Publisher: Addison-Wesley Professional
Year: 1999
Category: Computers

🎧 Free Preview Complete

You've listened to your free 10-minute preview.
Sign up free to continue listening to the full summary.

🎧 Listen to Summary

Free 10-min Preview
0:00
Speed:
10:00 free remaining
Chapter 11: Refactoring APIs
Key Insight 4 from this chapter

Preserve Whole Object

Key Insight

When a function is called with multiple individual values that are all derived from a single encompassing record or object, it is often better practice to pass the entire 'whole object' instead. This approach empowers the called function to extract the specific pieces of data it needs directly from the object. This method inherently improves the system's resilience to change, as future requirements for additional data from the object will not necessitate alterations to the function's parameter list, thus reducing the ripple effect of modifications.

Beyond future-proofing, passing the whole object also shortens parameter lists, making function calls easier to comprehend. Duplication of logic that manipulates subsets of an object's data can be reduced by moving such logic into the 'whole object' itself. A key exception to this refactoring is when imposing a dependency on the entire object is undesirable, particularly if the objects reside in different modules. The act of extracting multiple values from an object to perform operations is often a 'Feature Envy' code smell, frequently signaling that the associated logic should reside within the 'whole object'. This refactoring is especially useful after employing 'Introduce Parameter Object', consolidating various data clumps into the newly formed object.

The mechanics involve defining a new function that accepts the 'whole object' as a parameter, often initially with a distinct, searchable name. The body of this new function then calls the original function, correctly mapping the properties of the 'whole object' to the original parameters. Callers are subsequently modified to utilize this new function, a process that may render previous data extraction code obsolete and removable. Once all original call sites have been updated, the original function is inlined into the new one. Finally, the temporary name is removed from the new function and its callers. For instance, instead of evaluating `if (!aPlan.withinRange(low, high))` where `low` and `high` are separately extracted from `aRoom.daysTempRange`, the code can be simplified to `if (!aPlan.withinRange(aRoom.daysTempRange))`, with the `HeatingPlan.withinRange` method directly processing the `aNumberRange` object.

📚 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.