
-----------------------------------
wtd
Fri Oct 01, 2004 12:20 am

[Tip] Style: using indenting and spaces
-----------------------------------
Second C++ tip of the night.  

What

One of the keys to writing readable code is to properly use spacing and indentation.

Why

Readable code is easier to modify and debug.  You will get better feedback from others as well if you need help.  It will take others time just to figure out what your code is that they could otherwise spend figuring out what's wrong.

How


Indent code in braces

Anywhere code falls between curly braces ( { } ), indent it with a single tab or three or four spaces.  If you use spaces, do so consistently.

Wrong

int foo(int bar, int baz)
{
return bar * baz;
}

Right

int foo(int bar, int baz)
{   
   return bar * baz;
}

Wrong

if (wooble == 42)
{
doSomething();
}
else
{
doSomethingElse();
}

Right

if (wooble == 42)
{
   doSomething();
}
else
{
   doSomethingElse();
}

It Becomes more important...

When you have multiple levels of braces.

Wrong

int foo(int bar, int baz)
{
if (bar == baz)
{
if (bar < 42)
{
wooble();
}
else
{
fish();
}
}
else
{
ninja();
}
}

Very very right

int foo(int bar, int baz)
{
   if (bar == baz)
   {
      if (bar < 42)
      {
         wooble();
      }
      else
      {
         fish();
      }
   }
   else
   {
      ninja();
   }
}

Use space around operators

All too frequently I see code that looks like:

int wooble=42;
float foo,bar,baz;

This all perfectly valid syntax, but it flows so much better as:

int wooble = 42;
float foo, bar, baz;

I've got my fingers so well-trained to type the method with spaces that the first one was actually hard to type, so don't worry that it'll save you time to omit the spaces.

Also, it won't make your program smaller.  :)

This same principle can be applied to pretty much any operator.

Wrong

if (foo==bar)
{
   wooblize();
}

Right

if (foo == bar)
{
   wooblize();
}

Really wrong

if (foo==bar&&baz>wooble||ninja wooble || ninja 