Rules tell you what, principles tell you why

July 29, 2024

Key takeaway: When you add a rule to a team’s linter or style guide, write the reason next to it.

A rule is a principle with the reason removed. Learn the reason, and you’ll know when the rule fits and when to set it aside.

RuboCop’s Metrics/MethodLength flags any method over ten lines by default. The principle behind that number is that small units are easier to read, name, and test. A linter can’t judge readability, but it can count lines on every commit. That’s why rules scale, and also why they break: the reason doesn’t come along.

Say an eighteen-line method gets flagged. An engineer who only knows the rule splits it into process_part_one and process_part_two. The linter goes quiet and the code gets worse. An engineer who knows the principle asks whether splitting makes it easier to understand. If the method fetches, validates, transforms, and saves, those are real seams, so extract them with real names. If it’s one long SQL query or a case mapping error codes to messages, there are no seams. Disable the check for that method and leave a comment saying why.

“Always write tests” works the same way. The reasons are that tests let you change code without fear, document what it should do, and tell you quickly when you’ve broken something. If you know those, a one-off backfill script sorts itself out. So does the test that stubs a method to return 42 and asserts 42. It satisfies the rule and protects nothing. The reasons also show where the rule asks too little: daylight saving math, currency rounding, retry logic that only runs when a dependency is down.

The Zen of Python has the tension written right in. “Special cases aren’t special enough to break the rules,” then, “Although practicality beats purity.” You can only apply both if you know what the rules were for.

So when you add a rule, put the reason next to it, like a comment on each non-default linter setting or a “because” in the style guide. People question a rule with a reason when it doesn’t fit. Without one, they follow it blindly or ignore it.