Uncle Bob in Clean Code states, “the Boy Scout Rule tells us we should leave the code cleaner than we found it.” Another words, when we make changes to the code base, we should make sure we are leaving it (checking in to repository) cleaner.
The original rule of the Boy Scouts states: “Leave the campground cleaner than you found it.”
This is very relevant to the way we code!
Following this rule is not easy. In some cases it might not even be possible (most likely not a good sign).
Why isn’t it easy?
When I code, I try to follow similar, but fundamentally different rule: don’t make the code base worse than you found it. Worse, not necessarily better. Following this rule is not easy either. It means I have to get a good understanding of the code before I make a change. It means I don’t try to put in a quick fix or a hack, add special exceptions (wouldn’t it be easy to just add a simple “if” statement).
It all starts with one broken window, as the theory of a broken window tells us.
The Boy Scout rule takes it a step forward. It requires you to not only understand the code, but improve it before you check your code in. Just the other day, I saw something that smelled. It had a lot of duplication. My task was to add something similar. Since code was already written, somewhat complicated, I went with the easy route. I followed the same route: I added more duplication! I didn’t necessarily make the code base worse, as it’s already been like that. But I didn’t make it better either.
I did not follow the Boy Scout rule.
If I did, I would have taken the time to refactor the code, generalize it, and make it reusable. I would have removed the duplication and made it easier to modify later on. Read: I would leave it better than I found it.
I’m already feeling resistance. I’m thinking about situations where it might not be possible to follow the Boy Scout rule.
Resistance is good. It means that I have some growing to do. It means that following this rule is…
Yes, it’s going to be a challenge. But the reward is there. Making improvements to the system you’re working on is a reward on its own. Talking about this in an interview should also get me extra points. But most of all, following the Boy Scout rule will make me work harder. It will make me a better programmer.