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
}
The 7 Coding Styles That Are Dated.
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.
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.
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.
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With