White space matters in program source code

I'm Michael Suodenjoki - a software engineer living in Kgs. Lyngby, north of Copenhagen, Denmark. This is my personal site containing my blog, photos, articles and main interests.

Updated 2011.11.19 13:14 +0100

 

White space matters in program source code

In typography and layout it is a well known fact that white space matters[1]. Well put white space simply improves readability[2]. There should not be too little or too much white space. White space has to be placed just in the "right way". Several studies have been made which shows that this is true.

Studies in psychology confirm:

White Space improves the perception of information by 20%.[Lin, 2004]

What is the right way?

How to you measure the right way? Is it an objective truth? E.g. if you put white space like this you're guaranteed to have the best readability. Or is it influenced by subjective trends? One person can better read it in one way and another can better read it in abother?

I believe that there is some objective truths to this.

White space in C++ program source code

In programming, while editing/writing source code, I tend to believe that white space is just as important for improving readability and maintability of the source code.

As a C++ programmer I've seen many different uses of white space. We can divide the different uses of white space into issues which there is consensus about, i.e. everyone agrees to that and studies will back those, and issues that there is a debate on, i.e. consensus has not yet been reached and there are not yet studies available which can conclude which is best.

NOTE: For now this post is only describing white space issues in relation to using parenthesis.

Issues with consensus:

Debated issues:

In functional programming all statements are function calls, so I see no reasons why we should distinquish and use different spacing between function calls and statement keywords. This leaves us with the choice of whether we shuld use a space before left parenthesis in these or not. I believe the readability increases if the space is put after the left parenthesis rather than before.

To summarize - what is most readable?

1
int i = foo();
if( i>10 )
  i=10;
2
int i = foo ();
if ( i>10 )
  i=10;
3
int i = foo ();
if (i>10)
  i=10;
4
int i = foo();
if (i>10)
  i=10;

I go for 1!

Web Sources

Scolar sources

 

PS. It the right wording white space, whitespace or spacing?