Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coding style... error condition first or last?

Tags:

coding-style

Which is better in general in terms of the ordering? Do you put the fault condition at the top or bottom?

if (noProblems == true) {
    // do stuff
} else {
    // deal with problem
}

OR

if (noProblems == false) {
    // deal with problem
} else {
    // do stuff
}
like image 915
Larsenal Avatar asked Nov 24 '08 21:11

Larsenal


People also ask

How many coding styles are there?

The 7 Coding Styles That Are Dated.

What is Codestyle?

Programming style, also known as code style, is a set of rules or guidelines used when writing the source code for a computer program. It is often claimed that following a particular programming style will help programmers read and understand source code conforming to the style, and help to avoid introducing errors.

Is else if necessary?

No, It's not required to write the else part for the if statement. In fact most of the developers prefer and recommend to avoid the else block.


2 Answers

Maybe this depends on language conventions, or other factors, but I feel that the nominal case should be at the top, and branches should contain the exceptional conditions. It makes the code much easier to read. This is especially true when there are many exceptional conditions, and in most cases there are. You'll be able to easily assume that the author expects this specific path to be taken most of the time, and understand the code easier this way.

From "Code complete, 2nd edition" section 15.1:

By putting the most common cases first, you minimize the amount of exception-case handling code someone has to read to find the usual cases. You improve efficiency because you minimize the number of tests the code does to find the most common cases.

like image 63
Marcin Avatar answered Sep 19 '22 12:09

Marcin


i like to eliminate error cases first - and return from the function early so that the 'happy path' remains un-nested, e.g.

if (some error condition)
{
    //handle it
    return;
}
//implicit else for happy path
...

if it is easy to identify the conditions leading to the happy path, then by all means put that clause first (thanks Marcin!)

like image 43
Steven A. Lowe Avatar answered Sep 17 '22 12:09

Steven A. Lowe