Published April 14, 2020
by Doug Klugh
Organize Your Code
Refactor your code by grouping related statements together. This will promote Readability while setting you up for the next refactor — usually Extract Function. It is important to examine the code you are sliding and the code you are sliding over to ensure they do not interfere with each other in a way that would change the observable behavior of the system. As always, ensure reliable test coverage prior to refactoring and rerun tests often.
While many developers like to group their declarations together at the top of a method, a better practice is to declare elements close to where they are used. While this may not appear as pretty, it does make it easier to find and focus on related items. By sliding declarations down to their usage, it is also easier to refactor using Extract Function.
- A statement cannot slide up higher than an element's declaration that it uses.
- A statement cannot slide down beyond an element that references it.
- A statement cannot slide over any other statement that modifies an element it references.
- A statement that modifies an element cannot slide over any other statement that references the modified element.