From "Refactoring"
🎧 Listen to Summary
Free 10-min PreviewSeparate 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.