Write code to be read

Jan 28, 2021

TL;DR: write self documenting code. Use whitespace & DRY thoughtfully. Don't go wild with nested if statements.

In most situations, readable code is the best code. It will have fewer bugs and be simpler to maintain.

The meaning of 'readable code' is subjective, but it boils down to a bunch of micro decisions that we make when writing code, like:

  • "Should I make a new class or a function for this?"
  • "What do I name this variable?"
  • "How should I space things out with newlines?"
  • "Should I pull this code into a separate function?"
  • "What parameters should I accept?"
  • "Should I use an environment variable for this?"
  • And so on...

Here are my current thoughts on how to write more readable code:

  • Good variable names make your code self documenting. Most variables should not require comments.
  • Functions help document your code. If you're considering adding a comment to explain a fancy 20 line operation the middle of your code, it may be better off in a function.
  • Keep functions reasonably lean (< 100 lines?) so you can fit it all in your head at once.
  • If a line of code looks a bit complicated, refactor some of it into a variable. The code becomes more self documenting. And no, some extra variables are not going to hurt your performance.
  • Whitespace is a tool. Use it to group logically related chunks of code together. There are few things more intimidating in this world than a 200 line monolithic function with zero whitespace. In the name of joy and sanity, please group related lines together.
  • Avoid deeply nested if statements. Instead, use guard statements (that's their name in Swift, I'm not sure if there's another name for them) so the function's desired path is clear.
  • Avoid state where you can. Use classes sparingly. If in doubt, use functions or structs.
  • DRY is a tool. Don't obsess about it. Use it if it makes your code more readable (I went overboard with DRY when I started programming and made some terrible, complex monstrosities 😄).
  • [Added on July 2021] DRY doesn't just refer to refactoring similar functions. It's talking about source of truth. Do you calculate value XYZ in multiple places? Are there multiple ways for determining if a user has an active subscription? Everything becomes simpler when you have one source of truth for every algorithm and every state.

I'm looking forward to coming back to this article in the years ahead to see what holds true vs what changes in my opinion.