Barr Group TwitterBarr Group Vimeo

Rules:

8.2.a. It is a preferred practice that the shortest (measured in lines of code) of the if and else if clauses should be placed first.

8.2.b. Nested if…else statements shall not be deeper than two levels. Use function calls or switch statements to reduce complexity and aid understanding.

8.2.c. Assignments shall not be made within an if or else if test.    

8.2.d. Any if statement with an else if clause shall end with an else clause.13

Example:

if (NULL == p_object)
{
    result = ERR_NULL_PTR;
}
else if (p_object = malloc(sizeof(object_t))) // No assignments!
{
    ...
}
else
{
    // Normal processing steps, which require many lines of code.
    ...
}

Reasoning: Long clauses can distract the human eye from the decision-path logic. By putting the shorter clause earlier, the decision path becomes easier to follow. (And easier to follow is always good for reducing bugs.) Deeply nested ifelse statements are a sure sign of a complex and fragile state machine implementation; there is always a safer and more readable way to do the same thing.

Enforcement: These rules shall be enforced during code reviews.


Footnotes

[13] This is the equivalent of requiring a default case in every switch statement.

 

Comments:

Sometimes a final else statement is indicative of a programming error. I tend to use an assert() to capture the programming error prior to the if-else statement, which makes the final else unnecessary.

Should there be exceptions to the rule for this and for the do-nothing case?

I couldn't agree more than an un-handled final else case is indicative of potential bug. Indeed that's why we have this rule!

I applaud you for checking pre-conditions regularly with assert(). That is a fabulous practice that too few programmers engage in.

My best advice is to move the related assert() into the otherwise-empty else. And if there's nothing to do nor nothing assert there, then that at least merits a comment (explaining why) for the programmers who come along later.

By the way, there are several how-to articles of relevance elsewhere on our website:

What’s happening and how it’s done. Get in the know.

Sign Up for Our Newsletter

Receive free how-to articles, industry news, and the latest info on Barr Group webinars and training courses via email. 

To prevent automated spam submissions leave this field empty.