Style

Style

This is about what programs should look like

Rule 1 is to use a neat and consistent style

Rule 2 is for all members of a team to use the same style

Rule 3 is to avoid arguing or agonizing too much

The rest of the slides give some suggestions for you to choose from, based on personal experience

Line length

I suggest a maximum line length of 80 characters

Final newline

Every text file should have a newline at the end of the last line

Configure your editor, if necessary, to add it

Some standards and apps insist on it, it is a very widely supported convention

It is impossible to come up with a smooth convention without it (how do you create a text file with no lines?)

Soft tabs

Use soft tabs - hard tabs are obsolete and ambiguous

Use an indent of 4 spaces

The original indent of 8 spaces (also the original width of a tab) is too much

Aesthetically, it can be argued that the optimum indent is 3 spaces, but don't do that because many editors don't support it

So use 2 or 4, with the most common choice being 4

Use a common indent style


   Allman         Horstmann      GNU           Whitesmiths     K&R

   if (b)         if (b)         if (b)        if (b)          if (b) {
   {              {  x = 1;        {              {               x = 1;
      x = 1;         y = 2;          x = 1;       x = 1;          y = 2;
      y = 2;      }                  y = 2;       y = 2;       }
   }                               }              }

Hortsmann is aesthetically pleasing (the bracket columns line up, but you don't use up an extra line like Allman) but hardly any editors support it properly

So I suggest K&R or Allman (see Wikipedia)

Use explicit blocks

Don't do this, which causes many problems:

if (n < 0)
    n = -n;

Do one of these:

if (n < 0) n = -n;

if (n < 0) {
    n = -n;
}

Don't use end-comments

Don't do this:

n++;  // increment n

If you must put a comment inside a function, do this:

// increment n
n++;

End-comments come from assembly language, and from textbooks which explain how code works

Comments should explain what code does, and the code should be self-explanatory about how it works

Spacing

Spacing other than indenting is less important, but consistency aids readability and search/replace

I suggest the same conventions as in English text:

The most common exception is f(x) for function calling (no space before the open bracket)