HOME  PROGRAMMING  CONTACT   ABOUT


 
 


C, C++, C# and Java coding style


I'm pretty evangelical about source code formatting style >:D.  I truly believe the way you layout code heavily influences the quality of the code.
 
Indentation

Code should be indented with 4 space tabs.  Tabs are preferable to spaces because they can be adjusted and most editors recognise them.

Braces

Braces should be placed at the beginning of lines.  End braces should NOT be placed at the end of statements.  Placing braces at the end of statements makes code harder to understand.  Think of everything inside the braces as a block of statements with the braces acting as start and end markers.

Example:
 
// K&R style - Bad

if (x == y) {
   DoA();
} else {
   DoB();
}


// BSD style - Good

if (x == y)
{
   DoA();
}
else
{
   DoB();
}

 

Whitespace

Whitespace is very important.  You should always but spaces around operators (except for the dereference operators "." and "->") and new-lines before branch statements (break, continue and return).
 


Good style by example

Here's an example showing how K&R style formatting leads to confusing and hard to read code.
 
///
/// K&R formatting (evil)
///

void
Test()
{

     for(int i = 0; i < 10; i++){
         for(int j = 0; j < 10; j++){
            
for(int j = 0; j < 10; j++) {
                 Foo();
                 BarBarBar();
                 Xzy123();
             }
             Foo();
             Xzy123();
             BarBarBar();
         }
         Foo();

    
}
}

///
/// BSD style formatting (pure gold)
///

void
Test()
{

     for(int i = 0; i < 10; i++)
     {
         for(int j = 0; j < 10; j++)
         {
            
for(int j = 0; j < 10; j++)
             {
                 Foo();
                 BarBarBar();
                 Xzy123();
             }

             Foo();
             Xzy123();
             BarBarBar();
         }

         Foo();

    
}
}

Notice how easy it is to figure out which for-loop contains each call to Foo when NOT using the K&R formatting style?

When searching for the beginning of a logical block of code, it is arguably much easier for our brains to match a closing brace "}" with a starting brace "{" rather than with a keyword such as "if" or "for" or "do" or "switch" or ....well you get the idea. 

Everything contained within the start and end curly braces represents a single logical block of code and should be identified as such by starting the block on a new line.  Some people argue that doing this uses up too much screen space.  I'd have to say that if the function is too large to fit on one screen, you should probably consider refactoring your code!  Just think about how important white-space is in technical writing.  The same applies to code.

Writing good looking, easy to read code results in improved code quality and robustness.

 



Sun, 5 Feb 2012 04:27:09 UTC
 

enable trails