Write Code for Skim Reading

You can just read the title of this post and you’ll get the message!

Detail Needs Deep Reading

This came up when looking at some test code, but it applies equally to production code. Look at the following statement (scroll to read it all):

assertThat(isPublishingStatusPresent(id, CHANNEL_A, COMPLETED)).isTrue();

The challenge with this code is that you’ve a lot of symbols to parse (and scroll through) to work out what is being asserted. You need to consider the assertion, the function name, the operand of the function and then, finally, the comparison of isTrue at the end.

Think of Summarising It

The secret with code like this is to consider how you’d explain it to someone, or consider how you’d write it in pseudo code as comments.

Sidebar it used to be the recommendation to write a function as a series of pseudo code comments and then fill in the real code leaving the comments behind. I like this approach except the leaving the comments behind bit. You should think it through in terms of pseudo code and then leave self-explanatory code behind, extracting out functions or variables as necessary to make it make sense.

The above code is really just trying to say:

  • Under this use case
  • Assert That
  • The publishing status
  • Is True

The exact operand is a detail, and the skim reader just wants to know this is the true case of the publishing status.

Fix it with Formatting

A judicious use of whitespace will direct the reader to the above. A skim reader wants to just zip down the left hand side of the code to see what’s going on, and then can drill into detail if necessary.

assertThat(isPublishingStatusPresent(id, CHANNEL_A, COMPLETED))
    .isTrue();

You mean that’s it? Yes! Look at the left now. It reads, with the detail off to the side, like the description of the test.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s