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 1 from this chapter

Separate Query from Modifier

Key Insight

Functions that return a value without observable side effects are highly valuable assets in software development. They can be invoked repeatedly, moved freely within a calling function, and are simpler to test, significantly reducing complexity and potential issues. It is crucial to visibly differentiate between functions that alter data (modifiers) and those that only retrieve it (queries). A key guideline is that any function designed to return a value should ideally not possess observable side effects, although this principle is often adhered to as a robust recommendation rather than an absolute rule.

An 'observable side effect' refers to any change in an object's state that is discernible to external callers; internal optimizations like caching, which do not alter the sequence of query results, are not considered observable. The refactoring process begins by creating a copy of the original function, naming it to reflect its query aspect. The next step involves systematically removing all side effects from this newly created query function, leveraging the original function's return value as a guide for its intended purpose.

For each instance where the original method is called and its return value is utilized, the original call is replaced with an invocation of the new query function, immediately followed by a call to the original method (now acting purely as a modifier). The return values are then removed from the original method. For example, a function like `alertForMiscreant(people)` that finds a 'miscreant', triggers alarms, and returns the name, would be split into `findMiscreant(people)` (query) and `alertForMiscreant(people)` (modifier). The `alertForMiscreant` modifier can then be refined to `if (findMiscreant(people) !== '') setOffAlarms();`, and any resulting code duplication between the query and modifier can be subsequently addressed.

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