All three methods below are functionally identical - however they all have what I've perceived to be stylistical differences. When these are compiled, does the compiler treat them differently? (I lack the know-how to examine and understand the decompiled bytecode)
// Method 1
private boolean isAcceptableRange(final int a, final int b) {
if ((Math.abs(a - b)) <= range) {
return true;
} else {
return false;
}
}
// Method 2
private boolean isAcceptableRange(final int a, final int b) {
if ((Math.abs(a - b)) <= range) {
return true;
}
return false;
}
// Method 3
private boolean isAcceptableRange(final int a, final int b) {
if ((Math.abs(a - b)) <= range)
return true;
return false;
}
My initial thoughts are #1 will be unique due to the extra else
clause, where #2 and #3 will end up being identical. This would mean when optimizing for disk/rom space efficiency and possibly instruction efficiency (thinking embedded), go with option #2 or #3.
Or does the compiler know the end result and "optimize" it away?
I haven't looked at the bytecode either. But based on my general knowledge about compiler technology: if (condition) {then-part} else {else-part}
results in code that looks basically like:
if (!condition) branch to Label_1;
perform then-part;
branch to Label_2;
Label_1:
perform else-part;
Label_2:
In your example #1, the "then-part" is a return
statement. And the code for a return
statement would either be a return
instruction, or a branch
to some point at the end of the subroutine code where it does cleanup (including any finally
that's in effect) and then returns. And a decent compiler would not generate a branch (or any other code) following another unconditional branch or a return
instruction, since that code could never be executed. So example #1 would end up looking like
if (!condition) branch to Label_1;
set return value to "true";
return or branch to cleanup code;
Label_1:
set return value to "false";
return or branch to cleanup code;
And this would be the exact same code generated by examples #2 or #3.
So the answer to your question is: no, the compiler would not treat any of your examples differently, unless it is a really poor compiler.