As a kid, I used to play a game called “the floor is lava”. You’d try to cross the living room without stepping on the floor.
We’d do this by walking on the furniture – at least, when our moms weren’t around.
The secret to successfully crossing the room was to take many small steps, always checking that you had a solid foundation on the piece of furniture you were moving to.
You’d stand on the couch, put one foot on the coffee table, and test that your foot on the coffee table could hold your weight. You wouldn’t take your foot off the couch until you knew the coffee table could support you.
Kids who took big leaps usually ended up falling into the “lava”.
Changing an existing program is a lot like this game. To reduce your chances of falling into lava while refactoring, follow these four steps:
- Ensure the program runs before starting your change
This is vital when working on a team – especially if the team does not have good continuous integration with thorough unit test coverage.
I have had several experiences where I got the latest source code from the repository, made my change, and had an error while testing my change – only to discover (after much wasted time) that the error was in someone else’s change that was checked in to the repository.
Ideally, you’ll work on teams with good automated testing. But, sometimes you
- Add unit tests, if possible
Sometimes, when first starting to work on an existing program, you may not be able to easily add unit tests. The code may have so many dependencies (such as the database) that you cannot unit test anything.
In this series, I’ll show how I move my project from one with no unit tests to one that has a high degree of code coverage. Try to do this as soon as you can, so you can start adding unit tests.
- Make a small change
There is always a chance your change will not work. If you only changed one function, it’s easy to look at your change and try to find out what failed. If you added five new classes, and changed 15 existing classes, you might not be able to easily discover exactly what failed.
- Run your tests after making your change
If you don’t have unit tests in place yet, do manual tests that are as thorough as possible. Otherwise, you may be the person on the team who commits a breaking change to the source code repository.