Wednesday, January 20, 2010

Code convention and Coding practice

In a project, you would either be asked to follow few coding conventions or come up with the one that others can follow. The idea here is that the code written by two developers should not look completely alienated. But, it is unusual to have a list of coding practices for a project. Unfortunately I have seen developers often getting it mixed and think that following the prescribed convention would be hard on their existing coding practice/habit. So how are these different? Generally speaking, following (or not) certain coding convention could never be a cause of an spurious application behavior. Lets take few simple examples:
if(foo) {
  /* My great logic */
}
vs
if(foo)
{
  /* My same great logic */
}
or
void Foo::doBar(int a, int b)
{
}
vs
void
Foo::doBar(int a,
           int b)
{
}
Both of the above examples have no effect on the logical aspect of the application and therefore safely be categorized as a matter of convention. Whereas, good coding practice may avoid unintended application output and may even help with maintenance. For example:
if(foo == 1)
{
  /* My great logic */
}
vs
/* avoids "if(foo = 1)" typo error */
if(1 == foo)
{
  /* My same great logic */
}
or
bool Foo::doBar(int size)
{
  char *str = malloc(size);

  if(!doStep1())
  {
      free(str);
      return false;
  }  
  if(!doStep2())
  {
      free(str);
      return false;
  }

  /* More code here */

  free(str);
  return true;
}
vs
/* avoids cleanup error if more steps are added later */
bool Foo::doBar(int size)
{
  char *str = malloc(size);

  bool result = false;
  do
  {
      if(!doStep1(str))
          break;
      if(!doStep2(str))
          break;

      /* More code here */
      result = true;
  }

  free(str);
  return result;
}
The code fragments shown above may be logically correct and handling error properly in its current form. But as commented, the snippets on bottom the right are examples of good coding practices. This is also the reason two well behaved engineers may never agree on conventions, but may be following the same coding practice. I would be interested in learning about the coding practice that you follow including the ones in markup languages such as HTML and CSS.