The Boy Scouts have a rule: leave the camp cleaner than you found it. This does not mean that all the trash has to be cleaned up now, but you can’t let it get worse, and it must get at least a little better. In Bob Martin’s book, Clean Code, he asks, “What if code got a little better every time you change it?” I’ll answer it: the industry would not find itself in the mess it’s in. The industry norm is for code to incrementally worsen with each change.
Much of the time, following the Boy Scout Rule won’t be hard. It’s an incremental strategy. It’s easy to start and easy to sustain. Here are some typical challenges and ideas on how to be a Boy Scout.
Adding to a Long Function
Extract something; there must be plenty of opportunities to pull out some idea and name it. You want to add 3 lines, take out 5. Net improvement leaves a function 2 lines shorter. But I bet you can easily do better. Fix another complex conditional nearby to start a pattern of improvement.
Adding to a complex conditional
Extract the conditional into a helper function. Name it and its parameters well. Write a few tests for it. That’s picking up the obvious beer cans.
Look at the extracted code carefully. Does the conditional really belong with some other module? If so, the complex conditional is likely to be duplicated and the newly extracted function should be moved. Do the work or add it to your technical debt list.
You see a copy/paste/tweak opportunity that meets the functional requirements. Don’t do it, except maybe to test your hypothesis. Before, or after the change, do what the code is telling you: extract the common code into a helper function. Generalize and parameterize it so it handles both cases. Write tests around the code to be extracted to guard against breaking existing functionality. Make a list of the other previous cut/paste/tweaks of the same code for conversion.
Cryptic Local Variable Name
Once you figure out what the variable is for, rename it to help you, and your teammates, on the next code visit.
Pull out a nesting level or two into a helper function.
Broken Glass and Beer Cans in the Fire Pit
Put on some gloves. Clean out the big pieces of glass and cans. Bag the trash. A heavy duty bag is best. Be careful not to put any embers in the bag. Take the trash back to the boat.