0

Take for example the following two statements:

if (booleanVariable)
{
  doSomething();

  return true;
}
else
{
  return false;
}

and

if (booleanVariable)
{
  doSomething();

  return true;
}

return false;

Which one would be preferred?

They both return the same result in the end.

Any reason one would be better to use than the other?

Ryan
  • 1
  • 1
  • 1
  • See http://stackoverflow.com/questions/2677843/is-there-any-appreciable-difference-between-if-and-if-else – BoltClock Oct 21 '10 at 18:27
  • possible duplicate of [Why is "else" rarely used after "if x then return"?](http://stackoverflow.com/questions/3261849/why-is-else-rarely-used-after-if-x-then-return) – kennytm Oct 21 '10 at 18:28

3 Answers3

9

Personally, I think the cleanest way would be

if (booleanVariable) {
    doSomething();
}
return booleanVariable;

Moving the redundant returns outside the if block highlights what you are doing differently if the variable is set.

user470379
  • 4,879
  • 16
  • 21
  • Or, whenever booleanVariable is set to true (probably defaulted as false), immediately call doSomething(). Either way, it's less code. – Stefan Kendall Oct 21 '10 at 18:30
0

The if...else structure provides more readable code, but if you understand it fine and don't want to write as much, just do the second one :-)

0

I would have done it in different way. since, your first code solution might give an error, at least in c# since you will need to return a value outside of if-else scope.

i would have created a separate bool variable, and set it to true/false depending on what your if-test results

bool test;

if (booleanVariable)
{
  doSomething();

  test = true;
}

return test;

now if the if-test fail, the return bool will stay false as default.

Mana
  • 1,925
  • 6
  • 39
  • 55