Search code examples
language-agnosticlanguage-featuresreadability

What is the prefered style for single decision and action statements?


In the case of languages that support single decision and action without brackets, such as the following example:

if (var == true)
    doSomething();

What is the preferred way of writing this? Should brackets always be used, or should their usage be left as a preference of the individual developer? Additionally, does this practice depend on the size of the code block, such as in the following example:

if (var == 1)
    doSomething(1);
else if (var > 1 && var < 10)
    doSomething(2);
else
{
    validate(var);
    doSomething(var);
}

Solution

  • There isn't really a right answer. This is what coding standards within the company are for. If you can keep it consistent across the whole company then it will be easy to read. I personally like

    if ( a == b)    {
        doSomething();
    }
    else {
        doSomething();
    }
    

    but this is a holy war.