From "Refactoring"
🎧 Listen to Summary
Free 10-min PreviewSlide Statements
Key Insight
Code clarity is enhanced when related statements are grouped, particularly when multiple lines access the same data structure. The 'Slide Statements' refactoring moves code fragments to ensure related elements appear together, making the code easier to understand. A common application is declaring variables just before their first use, rather than at the top of a function. This refactoring often serves as a preparatory step for other refactorings, such as 'Extract Function' (106), as code must be co-located before it can be effectively extracted into a new function.
The process involves identifying a target position for a code fragment and examining intermediate statements for potential interference. A fragment cannot move backward past the declaration of any element it references, nor forward beyond any element that references it. Furthermore, a fragment modifying an element cannot slide over any statement that also references that modified element. Conversely, a fragment referencing an element cannot slide over any statement that modifies that element. Once safety is confirmed, the fragment is cut from its source and pasted into the target position, followed by testing. If tests fail, the slide should be broken down into smaller steps, either by moving over less code or by reducing the fragment size.
When determining if a slide is safe, one must assess if moving the code would change the program's observable behavior by checking for interference between the sliding fragment and the code it slides over. For declarations without side effects, such as 'let discount', or assignments to new constants, movement is relatively easy, allowing them to be placed closer to their usage or grouped for future refactorings. Code without side effects can be freely rearranged. However, when sliding code with side effects or over code with side effects, greater caution is required. A general rule is to avoid sliding one fragment over another if both refer to and one modifies common data. While this rule is not exhaustive for all operations, comprehensive understanding of how operations compose is crucial. Good test coverage is vital to confirm the safety of slides, especially with complex data structures, and in the event of test failures, smaller, more cautious slides or pre-refactorings like 'Split Variable' (240) are recommended. Sliding with conditionals can involve moving duplicate logic out of a conditional block, consolidating it into a single statement, or repeating logic into each leg of a conditional when sliding in.
📚 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.