Improve Code Readability with Spacing

I do code reviews for our developers. When I point out some of their scripts’ poor readability, nine out of ten times, they will react by promising to add some comments to their scripts.

But do you really need to use comments to enhance readability? Sometimes a few empty rows will do a great job.

What I have on my screen is very messy. I took the demo file from my Claris Engage session last year and removed all the spaces and comments from one of the scripts.

Sample script without spacing or comments

What does spacing tell us?

Why is this script so hard to read? Well, if you think about reading scripts like reading articles, a well-written article isn’t usually written in one large paragraph. Well-written articles are broken down into multiple paragraphs, with each paragraph conveying a distinct thought. All of these thoughts support a central idea.

A script should have a similar format. Each script step is an expression, like a sentence. A group of script steps represents a complete thought.

Spacing Conveys Logic

We should separate different thoughts from each other by putting some space in between them. This is because we tend to associate the physical distance between script steps with the logical distance between them. This effect is even more pronounced if you unfocus your eyes, which is usually what our eyes are like when we open up a script.

The openness separates things, whereas density implies close association. Script steps that are tightly related should appear vertically dense.

In addition to using openness and density to imply logical association, we should also be consistent when we use spaces. So I’m going to use 3 empty rows to separate thoughts that are far apart and 1 empty row to separate related expressions that are not that close. For expressions that are closely related, there should be no space between them:

script with proper spacing
Use density to show if script steps are closely related

As you can see, with spacing alone, we have greatly enhanced the readability of this script.

More Resources on Code Readability

But what about comments? Is using comments wrong? What are considered good comments and what are considered bad ones? I will talk about good comments vs. bad comments in my next article.

If you like this topic, this related video is a great resource. We’d also recommend this article on how we tend to add rather than subtract when problem-solving.

For more information on code readability, we have articles on why it’s important and on naming conventions that will help improve code readability. You can also check out this video on our YouTube channel.