3

A professor told me long ago to use else when "chaining" multiple conditions in a series (I was still learning). Now that I've been tinkering with several frameworks and CMS years later, I find it quite amusing that what I was taught to do isn't necessarily so.

I was taught to use else in between a series of conditions:

function double(param){
    if(param==1){
        return param+=1;
    }
    else 
    if(param==2){
        return param+=2;
    }
    else{
        return false;
    }
}

Nowadays, I seem to see this, which I was warned long ago NOT to do:

function double(param){
    if(param==1){
        return param+=1;
    }
    if(param==2){
        return param+=2;
    }
    return false;
}

This sample code might not work, but the idea is there: Is it necessary to use else in between every condition? If so (or not so), what should I look out for when using either way? There must be something that caused my professor to tell me such thing.

c69
  • 19,951
  • 7
  • 52
  • 82
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • 5
    Just as a comment on the use of white-space, a newline between else and if in an "else if" is *extremely* confusing (and I've never seen it before). Also I suggest removing the language tags since this applies to pretty much every language out there. – John Carter Jan 29 '12 at 00:44
  • @therefromhere my apologies, i was on PHP. then the white-space was just for clarity of the `else`. although, sometimes i do code that way to see the `else` apart from the `if`. – Joseph Jan 29 '12 at 00:50
  • 1
    `else` is redundant here, because you have `return` in your code, which will end up function execution anyway. Also, whole function can be written as `function (n) { if( n==1 || n==2 ) { return n*2; } return false; }` – c69 Jan 29 '12 at 00:51
  • 2
    The "return else" question is long debated. I trend away from "return else". related thread: http://codereview.stackexchange.com/questions/2084/if-return-else-return – Umbrella Jan 29 '12 at 00:55
  • @c69 it's just sample code :), no need to simplify. although you have a point about redundancy. – Joseph Jan 29 '12 at 00:58
  • 1
    https://developer.mozilla.org/En/Developer_Guide/Coding_Style gives a reason of "it increases indentation levels", which, in non-trivial examples can make a big difference in readability. – Umbrella Jan 29 '12 at 01:02

8 Answers8

4

Using else or not using it mean two different things.

When you wish to test a series of conditions where at most one may be true, use else or else if. When one condition evaluates true, the code in the block is executed and then the entire if-else construct is exited.

When more than one condition may be true, using else will preclude other conditions from evaluating to true, and so it would be wrong to use an else in this situation.

Edit: I now see you are referring to the specific case where each clause contains a return statement. In this case it is probably better to use an else or elseif to make it clear that the if-else construct behaves in the first manner - ie. at most one condition may execute.

ose
  • 4,065
  • 2
  • 24
  • 40
  • 1
    +1 Agreed! It's good coding practice to use techniques that make the code more readable. We're engineers. We're not playing where's waldo with our code :) – jamesmortensen Jan 29 '12 at 00:47
  • @jmort253 Actually, apparently some very bored people are: http://stackoverflow.com/questions/8479058/how-do-i-find-waldo-with-mathematica – annonymously Jan 29 '12 at 03:38
2

It is not necessary to use else, as the control flow returns from the function immediately at the point of the return keyword.

Further, I find using else when there is a return unnecessarily confusing, and so would prefer alternative 2 in all cases.

JRL
  • 76,767
  • 18
  • 98
  • 146
2

It's really just a matter of opinion.

It's not necessary to use else in a case such as this, however your professor may have been describing a different case, or perhaps he was simply having you do it for emphasized/forced clarity.

First of all, it's my opinion that returning different data types from the same function is generally bad style, but having said that, take your example:

function double($param) {
    if ($param == 1) {
        return $param + 1;
    } else if ($param == 2) {
        return $param + 1;
    } else {
        return false;
    }
}

Now imagine a similar example, except it doesn't return each time:

function double($param) {
    $returnMe = 0;

    if ($param == 1) {
        $returnMe = $param + 1
    } else if ($param == 2) {
        $returnMe = $param + 2;
    } else {
        $returnMe = false;
    }

    return $returnMe;
}

This may seem trivial (and in the examples provided it largely is), you can see that the else really does make a difference.

In forcing everything to have an else like he did, he was probably just trying to provide some consistency in style (which I'd argue is good for newcomers).

Of course, you are right, in the case you presented, having the else was unnecessary. Whether or not it's bad or good is really just a matter of opinion.

Bhaxy
  • 5,346
  • 10
  • 39
  • 41
1

Scenario 1

if ($one) {
    doA();
}
if ($two) { // ALWAYS check this block - it is not attached to anything
    doB();
}

Truth table:

            | $one True | $one False 
------------+-----------+------------
$two True   | A and B   | B only   
$two False  | A only    | none

Scenario 2

if ($one) {
    doA();
}
else if ($two) {  // ONLY check this block if $one is false!
    doB();
}

Truth table:

            | $one True | $one False 
------------+-----------+------------
$two True   | A only    | B only   
$two False  | A only    | none

As you can see in the truth tables, the two scenarios are not the same. So, whether to use if..else or if..if is not just a matter of semantics or taste, it has an actual functional difference.

In the case of returns inside of an if, it will exit the function entirely and therefore it is a special case where the result is the same as an else-if.

Nicole
  • 32,841
  • 11
  • 75
  • 101
0

I think it's a good practice, becouse the flow would follow down if you forget the return clause (leading to hard-to-find bugs)

Anyway, the else clause may be too verbose in some situations, so you can use elseif:

<?php
if ($a > $b) {
    return "a is bigger than b";
} elseif ($a == $b) {
    return "a is equal to b";
} else {
    return "a is smaller than b";
}
?>
santiagobasulto
  • 11,320
  • 11
  • 64
  • 88
0

Yes. Why? Because these conditions are based on the same variable and only one can be met. For this reason, if you use elseif (PHP) or else if (JavaScript), you will improve code visibility and possibly avoid some future errors.

Your code in PHP

Your code in PHP would look like this:

function double($param){
    if($param==1){
        return $param+=1;
    }
    elseif($param==2){
        return $param+=2;
    }
    else{
        return false;
    }
}

or, using switch counterpart:

function double($param){
    switch ($param) {
        case 1:
            return $param+=1;
        case 2:
            return $param+=2;
        default:
            return false;
    }
}

Your code in JavaScript

In JavaScript it would look like this:

function double($param){
    if($param==1){
        return $param+=1;
    }
    else if($param==2){
        return $param+=2;
    }
    else{
        return false;
    }
}
Tadeck
  • 132,510
  • 28
  • 152
  • 198
0

it really depends on the flow of your codes... sometimes you need to use separate if(s), and sometimes you need to use if(s) and else(s)... but for the sake of the example you added. personally, I'd select the first one you wrote because its more efficient and easier to read and understand. perhaps there are other factors and points but that's how I see it and that's why I chosen the first one..

one more thing to add.. is that if you use the second one the compiler will always execute the second "if", if the $param was containing a different value other than "1" or "2".

Desolator
  • 22,411
  • 20
  • 73
  • 96
0

You may fancy this scenario I spotted not too long ago on Apple's website

switch(true) {
    case foo == bar:
        break;
    case foo > 5:
        break;
    case foo > 10:
    case bar > 5:
        break;
}

You get the idea. I believe all compilers break this down to if/else code, but I like the flexibility of controlling where the break statements are.

Jacksonkr
  • 31,583
  • 39
  • 180
  • 284