Breaking Rules - Part 1: Sandi Metz

Rules are great, and nearly everybody likes to break them so this series will explore how and when it's appropriate to break rules. There is a (trite) philosophy stating

Learn the rules well so you can break them properly

This post attempts to break down how or when to "properly" break some specific rules.

Sandi Metz has four rules (or five or six) for writing Ruby (and Rails) code

  • Classes can be no longer than one hundred lines of code.
  • Methods can be no longer than five lines of code.
  • Pass no more than four parameters into a method. Hash options are parameters.
  • Controllers can instantiate only one object. Therefore, views can only know about one instance variable and views should only send messages to that object (@object.collaborator.value is not allowed).

She mentions in this podcast that people frequently quote her rules while forgetting the most important one:

The [last] rule is that you can break any of [the others], as long as you can get your pair to agree.

She goes on:

Why is it that we're such cargo-culters about things?

That's the rule that people forget!

This is a beautiful reason to break a rule. In writing code, you and your pair are codifying the logic of the domain. The most important thing is to keep that code easy for others to understand and modify as the demands of the domain change. That is why Sandi's rules can be so helpful; they make it harder for you to write complex, difficult-to-understand code. However, these rules do not always apply and there are valid reasons to break them.

Working with a pair or code-reviewer is great because together, the team can write better code.

If you have a strong and empathetic working relationship your pair then you will be able to make good decisions together. These rules are heuristics to prompt discussion about whether a particular choice is "good." As professionals, we must be confident in breaking these rules, but only with good reason: we must convince our pair.

Note:
I mostly write this blog for myself. Writing this post was a lot of fun for me in that I went back and listened to some old podcast episodes, watched the conference talk, and then spent a bunch of time figuring out what I actually wanted to say. I highly recommend checking out the links below. Those people are smarter than me and have great insight. If you come to different or other conclusions then feel free to reach out. I love talking about this stuff!