What should you do when you have several if statements in a row? Some people like to nest if statements like this:
foo = 0; if (x) { // Do work … if (y) { // More work … if (z) { // Final calculation … foo = x + y + z; } } } return foo;
Others prefer to check conditions one after another, like this:
foo = 0; if (!x) { return foo; } // Do work … if (!y) { return foo; } // More work … if (!z) { return foo; } // Final calculation … return x + y + z;
I prefer the second method. Nesting if statements can get confusing; the second style looks cleaner and tells the reader immediately when they can return. I also feel that the second style is more concise. It helps keep code within an 80-character width limit.
Some programmers might argue that the second style leads to duplication of code (“return foo” is copied three times). However, if that fragment (“return foo”) becomes complex, it could be moved to a separate method and called three times. I think that’s a fair price to pay for readability. After all, the compiler will optimize both styles into the same machine code.
Which style do you prefer, and why?