Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If 'else' is about to happen anyway should it be declared or not? [duplicate]

Possible Duplicate:
Should ‘else’ be kept or dropped in cases where it’s not needed?

When

a = 0

This:

var foo = function() {
  if (a != 0) return true
  return false
}

Or this:

var bar = function() {
  if (a != 0) return true
  else return false
}
like image 231
stagas Avatar asked Aug 26 '10 12:08

stagas


5 Answers

You should do whatever makes the code clearer.

like image 119
Russ Avatar answered Nov 02 '22 10:11

Russ


It gets optimized at compile time anyway, so no runtime difference.

As usual, you can argue about style. My 50 cents: the first variant (no explicit else) is nicer because it's less code doing exactly the same.

Of course, in this case, you would do

return a != 0;

... but I think the question is meant to be general.

like image 45
Michael Avatar answered Nov 02 '22 09:11

Michael


I would say it's a good practice to do so, because it would make changing the code a bit easier. For instance, let's say you wanted to print out the result. You could either change it like this:

if (a != 0) {
    print "returning true"
    return true
}
print "returning false"
return false

Which means adding a print twice, or else:

if (a != 0) {
    retval = true
} else {
    retval = false
}

print "returning ", retval
return retval

which means adding one print, but this won't work without the else.

Of course, this is a contrived example, but it shows how you should try to make your code as maintainable as possible.

like image 6
Nathan Fellman Avatar answered Nov 02 '22 10:11

Nathan Fellman


As the compiler will probably reduce it to the same compiled code anyway, do what you believe to be more "beautiful".

Note that code elegance is subjective, so dogmatically clinging to one format or another is unnecessary.

like image 3
kbrimington Avatar answered Nov 02 '22 11:11

kbrimington


if(statement)
       result = true
else
       result = false

return result
like image 2
Dominique Avatar answered Nov 02 '22 09:11

Dominique