The “Boy Scout rule” in programming states that we should:
Always check a module in cleaner than when you checked it out.
I follow this rule when I make updates on existing codebases, and I use updates as an opportunity to refactor a section of a codebase that I’m already modifying. Sometimes these refactors are small, and only amount to updating a specific function, or even a few lines in a function. Sometimes, however, I will refactor an entire file. In those cases, it’s helpful to follow a few rules:
- A refactor should not change the public API. This means that any functions or class methods that are exposed for use by other code should not change their method signature or return values.
- All tests that were previously passing should pass after the refactor without needing to modify the tests themselves (unless there was an error in the test that was exposed by the refactor, which happens more often than you’d think).
- If you’re taking the time to do a refactor, ensure that whatever you touch is brought up to the latest coding standards, including adding or modifying docblocks.
One trick I use when refactoring an entire file is to add a line to mark my place, since I tend to move method definitions around to group them by visibility (in classes) and sort them alphabetically (because I’m a pedant). Most IDEs will highlight TODO lines in a different, brighter color, so I use the following to mark my place:
// TODO: REFACTOR LINE
It’s also useful to refactor one method at a time, and run tests after each, to catch any breaking changes right away.