Nothing is Something

When it comes to writing correct, efficient, usable, extensible, readable, and supportable programs, many things come into play.  Coherent algorithms, usage of proper data structures, intelligent application of OOP principles, application of existing standards and conventions, expertise in the domain or business logic, etc.  We can probably keep brainstorming here until we pass out, and produce a list of platitudes long enough to gag a horse.

What I’d like to do is to get back to two simple things that can aid tremendously in some, if not all, of the criteria I use to rate a great program.  They both pertain to what is essentially nothing.  I.e., they do not contribute to the solution of the problem, nor do they increase a program’s efficiency.  They do not make the program more reliable, nor particularly more usable.  In fact, if you never have to really read the code, they make no difference to you at all, because by the time the program is running, the compiler has discarded them.

The two items I’m talking about are comments and space.  Beyond the utter disregard they suffer at the hands of the compiler, they share a kind of symbiosis.  In some ways, good spacing is commenting, and good commenting can add to better spacing.

Back in the mists of time, when I was learning assembly language, my instructor fanatically insisted that I put a comment on every line, without exception.  There was some rationale for this.  Assembler by its nature is very concise, almost cryptic.  It is also very low-powered: it takes a lot of code to do some very simple functions.  Without a clear description of the thought process for these atoms of logic, assembler can be virtually impossible to read.  Most of us today can avoid the challenges that assembler presents, and so a religious dedication to commenting every single line is no longer necessary, and frankly, can detract from readability if applied too scrupulously.

Today we have some languages in our toolboxes that bring us close to the Holy Grail of self-documenting code.  (Something COBOL was supposed to be, but I never got the chance to find out.  Reports from the front were not good!)  Some of the aids:

  • Variable names of unlimited lengths
  • Naming standards for variables (e.g. as we covered to death here and here)
  • Auto-commenting features (/// in C#, /** in Java, ”’ in VB, e.g.)
  • IDE plugins to assist in comment headers
  • A convergence of common statements, i.e. if, while, for, switch, etc. are all very similar among, C, C++, C#, Java, Perl, PHP, JavaScript, etc.

In the code I write today in C#, I find that the vast majority of my lines really do not require any comments.  If I am adhering to reasonable variable naming conventions (e.g. using NumberOfItems, not noits), and have provided solid comment headers at the top of my functions, then comments within the body of the function code are only necessary in these cases:

  • Tricky code–code that needs further explanation because it’s obscure.
  • Explanations why an obvious method was not used, e.g. I use a series of if…if else…else statements rather than a switch because one of my cases would require a non-constant value, and C# does not like that.
  • Warnings about problems that might occur if the business logic changes.
  • Warnings about lines whose proper order is critical to correct processing.
  • Use of any “magic numbers” or “magic strings.”  Although these should always be defined as consts someplace, it’s always good to remind the reader of their significance.

It is possible to overdo the commenting to be sure.  E.g a comment such as the one below is pointless:

if (ItemWasProcessedOK)
   NumberOfItems++;   // Increment the number of items if it was handled successfully

It’s silly because the comment adds nothing to the understanding of the statement.  Any reader should be expected to know what the ++ operator does, and the variable names are sufficient to explain the intent of the coder.  In this case, the comment actually detracts from the readability of the program because it slops up the code space with useless characters.  This kind of thing is almost as bad not explaining your tricky code–almost.

Spacing is something of a more refined art.  There is good space and bad space.  Good space breaks up a block of code into more readable sub-blocks.  Bad space just spreads out the code so it expands beyond the window of your screen and makes you scroll to read the function, which as mentioned last time, is a Bad Thing.

E.g. a block of code such as this:

if (x == 9)
    // Do something
else
    // Do something else
var y = new Thing1();
var z = new Thing2();
if (a == 10)
    // Do something
else
    // Do something else

Can be rendered more readable by the judicious application of blank lines, like this:

if (x == 9)
    // Do something
else
    // Do something else

var y = new Thing1();
var z = new Thing2();

if (a == 10)
    // Do something
else
    // Do something else

However the following spacing:

if (x == 9)

    // Do something
else
    // Do something else

var y = new Thing1();

var z = new Thing2();

if (a == 10)
    // Do something
else

    // Do something else

Indicates one of the following:

  • The coder is careless or sloppy.
  • The coder has some kind of handicap (pun intended) where s/he cannot control how many times s/he strikes the ENTER key before typing the next statement.
  • The coder is demonstrating that s/he writes code as a stream-of consciousness exercise, and never goes back over what was written.
  • The coder intended to add some more statements but could not bear to go back and add them because it would have been, like … a total drag, man.
  • The coder just doesn’t give a crap.

None of the above is the kind of coder I want writing code for my company.

If for some reason you feel strongly that the following code:

if (iNumberOfItems == 0)
{
   Console.WriteLine("There were no items");
   return false;
}

Is rendered more readable by doing this:

if (iNumberOfItems == 0)
{

   Console.WriteLine("There were no items");
   return false;

}

(Which leads me to question your sanity, but OK.)  Then, dammit, there’d better be an extra line below every left brace and an extra line above every right brace in your code, or else you need to go to the bullet list above and pick one.

In case you cannot pick up on my subtle humor here, I am defiantly against inserting gratuitous blank lines for no good reason, because they violate the principle of What You See Is What You “Get.” And while one blank line can be useful, two or more is does not make it even better.  Frankly, if Visual Studio did not default to the first code snippet’s format above, I’d probably still be rendering it like this:

if (iNumberOfItems == 0) {
   Console.WriteLine("There were no items");
   return false;
}

And saving myself a line.  (A grudging nod here to JavaScript which really wants that brace on the same line.  Unfortunately if you put it on the next line, JavaScript sometimes does stupid things, which is just wrong.)  Remember, you have about a 2:1 ratio of horizontal to vertical space at the 75 lines by 150 columns we discussed before.  Vertical space is way more precious.  Consume it carefully; don’t waste it.

Hell, I still pull this kind of stuff in Perl, mostly because it pisses me off that I have to use those braces:

if ($x == 0) {
    $Message = "Zero";
} else {
    $Message = "Not zero";
}

(OK, so I’m kind of fast and loose in Perl, but c’mon, Perl is a fast and loose language, so, ya know, When in Rome…)

My point is that C# and VS’s default editing settings force you to put each brace on a line by itself.  Sure, I can change the setting, but if you’re working in a group, and you’re the only one who’s twiddled with the default edit settings, then your code sticks out like the proverbial Sore Thumb.  So there’s a lot of readability vertical spacing already built into the IDE.  And, yes, it helps if all the code in the project looks similar.  But don’t go crazy adding extra blank lines where none are needed.

One last thing to mention is: don’t underestimate the power of horizontal spacing.  This takes some extra dedication, and sometimes the IDE battles you on this, but e.g. a lot of assignments can be rendered way more readable with some extra spacing:

string Division = "American League East";  // The toughest division in the game
string First = "Yankees";  // What else is there to say?
string Second = "Blue Jays";  // Good team, maybe Toronto should move to the west a bit
string Third = "Orioles";  // Maybe they will surprise themselves
string Fourth = "Rays";  // They look good down here
string Fifth = "Red Sox";  // May they remain here forever!
var When = new DateTime("4/16/2011");

Looks a lot better when you do this:

string Division = "American League East"; // The toughest division in the game
string First    = "Yankees";              // What else is there to say?
string Second   = "Blue Jays";            // Good team, maybe Toronto should move to the west a bit
string Third    = "Orioles";              // Maybe they will surprise themselves
string Fourth   = "Rays";                 // They look good down here
string Fifth    = "Red Sox";              // May they remain here forever!
var When        = new DateTime("4/16/2011");

(I suppose one grand assumption I’m making here is that your font selection in the IDE is mono-spaced. If you use a proportional font, this won’t matter, and your code will suffer from that no matter what you do!  I honestly don’t understand why anyone would use a proportional font.)  A similar mechanism works well for function calls with a large number of arguments.  I realize there are some hazards doing this, what with Visual Studio always want to re-format your code blocks when you close them, and some tedious typing is involved, but I think the clarity it brings to the code page is worth it.  I suppose this is some of my assembler background coming through!

There was a lot here today amongst the wise cracks, so to summarize:

Use space judiciously, not gratuitously; you have more horizontal columns than you do vertical lines, so use the latter carefully; comment but don’t comment too much or for no reason; line things up to help the reader’s eye.

This entry was posted in Readability, comments and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>