Thursday, October 09, 2008

Compact Coding should not hamper readability

Compact Coding should not hamper readability

One of the most important coding practice that programmers believe is to have the conditions compacted to prevent a larger amount of code block on a particular condition. For example,

if (condition)
//do something
else if (condition)
// do something
else if (condition)
// do (something)
else if (condition)
// do something
else
// do something.

This is the startup style of writing the logic. There are two other ways of writing the same block.

  1. Ternary Operator: We can have nested ?: to bring in these conditions and these would get squeezed into a single line. For the compiler, it is fine as long as the parenthesis is properly closed and the syntax is adhered to. For when it comes to debugging an issue or maintaining this code at a later point of time, even for the same developer down the line after six months, it would really be a severe nightmare.
  2. Switch Case:

    switch (condition)
    {
    case expr1:
    //do something
    break;
    case expr2:
    //do something
    break;
    case expr3:
    //do something
    break;
    case expr4:
    //do something
    break;
    default:
    break;
    }

    I would say switch-case is more cleaner in the following perspectives:
    1. The condition is just evaluated once and the individual expressions are just matched later.
    2. The code flow is quickly comprehendable by any one at a later point of time.

The art of coding is to get the thing done not only correctly but also in a clear unambigous terms.

No comments:

[Imported from Blogdrive]Online Virus Scanners

Online Virus Scanners Virus Scanners are no longer difficult to install, tedious to configure. There are easy to use Online Virus Scanne...