First published at Tuesday, May 30, 2017

This blog post has first been published in the Qafoo blog and is duplicated here since I wrote it or participated in writing it.

Refactoring with the Advanced Boy Scout Rule

When we join teams to coach them with refactoring their legacy code base, many of them are overwhelmed by the sheer mass of code. That typically results in the request for "some refactoring sprints" or even "a complete rewrite". Both is obviously not a solution from the business perspective - feature development and bug fixing needs to go on and the refactoring should not eat up the larges portion of time. But where and how should the team start and how should? What we call the "Advanced Boy Scout Rule" has helped many teams to come over this staleness and reach fast results while continuing to deliver business value.

The Boy Scout Rule says

Always leave the camping ground cleaner than you found it.

Or translated to software development

Always leave the code cleaner than you found it.

This mantra is hopefully part of your team philosophy latest since every member read "Clean Code".

Building on this idea we apply the "Advanced Boyscout Rule" as follows:

  1. When you feel pain while working on a specific code piece, stash your changes and try to resolve the pain through refactoring right now.

  2. If you managed to fix it, commit and resume your original work.

  3. If you did not manage to resolve the issue within $x (maybe 15-20) minutes:

    • Revert the refactoring attempt

    • Add a @refactor annotation describing shortly what your issue is

    • If there already is a @refactor annotation, append a ! to it

  4. After 1-2 sprints, grep your code for @refactor and sort the output by the number of ! descending.

  5. Pick the highest priority issue(s), define a solution strategy and add regular tickets to execute the refactoring in the upcoming sprint.

This procedure yields you several benefits, like:

  • Code becomes better and better in small steps every day

  • You reach the most hurting pains first, improving every day development fast

  • Immediate visible business value from your development is not lowered significantly

  • Instead, you even gain business value by stabilizing the parts of your software first which are touched most

Of course this is only a draft for the concrete implementation in your team. You should change this accordingto your needs. For example instead of leaving comments in the code, some teams prefer to add a post it with the class name to a wall in the office and add dots on their back if there is already one. For other teams it makes sense to focus on specific aspects first like "extract SQL statements into gateways/repositories" or "migrate from arrays to data transfer objects".

I'd like to thank Michael Marlberg who made me aware of this method at first in a project we worked on together.