You will see it everywhere:
if (condition) { return var; } // by nature, when execution reaches this point, condition can only be false, // therefore, the else is unnecessary return other_var;
In most cases, adding an else clause is not only optional in this case, but many times, it is optimized by the compiler.
Think about how the computer thinks about this code (in terms of machine code simplified for pseudocode here for demo purposes):
0x00: test [condition] 0x01: if result of test was not true, goto [0x04] 0x02: push [var] onto stack 0x03: goto [0x05] 0x04: push [other_var] onto stack 0x05: return from subroutine
The code (again, this is pseudocode, not assembly) will act in exactly the same way for conditional if/then/else .
Many people believe that bad and / or confusing practice has several possible exit points for a function, since the programmer must think about every possible path through his code. Another practice is as follows:
return (condition) ? var : other_var;
This simplifies the code and does not create any new exit points.
amphetamachine Jul 16 '10 at 4:24 2010-07-16 04:24
source share