Video in progress

What is the "boy scout rule", and how much refactoring do you do while working on a feature?

"Leave the code a little cleaner than you found it." Small improvements in the places you touch, like a name, extracting a method, deleting dead code, go along with the feature. A big refactoring should be in a separate PR, otherwise review and rollback get harder.

📖 Answer

In practice I draw the line like this:

OK inside the feature PR:

  • renaming an unclear variable;
  • pulling 20 lines out of a method I'm changing into a separate method;
  • deleting an unused import, commented-out code or a dead if branch;
  • adding a missing test (so that my later change is safe).

Needs a separate PR:

  • splitting a class, moving packages;
  • a change that touches the public API or the DB schema;
  • rewriting a module that I haven't touched but "looks bad".

The reason is review. If a 40-line feature and a 600-line refactoring are in one diff, the reviewer won't see the bug in the feature. And if there is a problem in prod, you can't revert just the refactoring.

A useful habit: make the refactoring commits separate ("rename", "extract method", where behavior didn't change) and the feature commit separate. The reviewer then sees them one after another.

The boy scout rule has a limit too: if the code isn't covered by tests, "cleaning up" can change its behavior. Test first, then clean up.