11

What is the best practice to end an if...else statement without an else condition? Consider the following code:

$direction = $_POST['direction']; //Up or down

if ($direction == "up") {
  code goes here...
}

elseif ($direction == "down") {
  code goes here...
}

else {
  //do nothing?
}

As you can see, there's only 2 condition; either up or down and the else statement doesn't really have a purpose unless you want it to display an error message.

Most of the time I see programmers simply put the else condition there but inserts a comment instead of any working code like this.

else {
      //error messages goes here...
}

or just assume if it's not 'up' then everything else should be 'down' since there's only 2 condition. If a user inputs 'left' or 'right', it would still be considered as 'down'. I think this is somewhat inappropriate.

if ($direction == 'up') {
  code goes here...
}

else {
  code goes here...
}

I know that PHP would still work if we put if without else condition. But what if there is an elseif condition? In cases like these, what is the best practice if we want to maintain a strict if...else statement if we do not want to include any error messages or have any else conditions?

Thanks in advance.

Jon
  • 428,835
  • 81
  • 738
  • 806
John Citizen
  • 119
  • 1
  • 1
  • 3
  • 3
    As far as I am aware it is not considered "bad practice" to not include an else condition by any means. You just do what the script calls for, if there should be no default response to something, then don't have one. – Jim Mar 15 '11 at 15:13

6 Answers6

22

There is no if...else statement.
There is only an if statement that can be extended with else and elseif operators.

So, the best practice on if statement without else condition is an if statement without an else condition:

if (condition) {
  //some code
}

Frankly, there is no best practice. The best practice is just one that follows the program logic.
That's all

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • 2
    It's kind of a generic answer that misses the point, I think. – Core Xii Mar 15 '11 at 15:35
  • 1
    @Core I think it's rather question that missed the point;) Ask me certain question and you'll get certain answer – Your Common Sense Mar 15 '11 at 15:39
  • 1
    I agree, the question isn't as clear as it could be, and in that regard your answer is precise; But I'd rather fix the question than up-vote the wrong answer. – Core Xii Mar 15 '11 at 15:50
8

Don't write empty elses. This would just clutter up the code, and it's perfectly obvious what you meant.

In many cases, you can actually use the switch statement:

switch ($_POST['direction') {
case 'up':
     // code ...
     break;
case 'down':
     // code ...
     break;
default: // else
     throw new Exception('Invalid direction value');
}
phihag
  • 278,196
  • 72
  • 453
  • 469
  • But, wouldn't the `default` in this case act as an else statement? :) To answer the question to the OP's liking, you would want to remove the default statement. As it is not a requirement to be in the switch. However, you do not have to write empty `else`'s either. You just have to omit them. – Jim Mar 15 '11 at 15:15
  • I think a switch is the best option in this case. – SecretDeveloper Mar 15 '11 at 15:16
  • I would `throw new Exception()` at the `default` if `"up"` and `"down"` were the only allowed values. – Core Xii Mar 15 '11 at 15:21
  • @Core Xii Excellent idea! Updated. – phihag Mar 15 '11 at 15:23
  • Can't take credit for it though, that's how [D does it](http://www.digitalmars.com/d/2.0/statement.html#SwitchStatement). And I prefer it that way. If you want a `default` that does nothing, you should explicitly say so. – Core Xii Mar 15 '11 at 15:38
1

I think that if there's nothing to do on else, then there's no need for else block to exist in code. If else block is included, it means that it has a purpose to be there, so the code is incomplete yet, if it is empty.

binaryLV
  • 9,002
  • 2
  • 40
  • 42
1

This isn't something that can take a definite answer. Here's my take, it would be interesting to see what other opinions exist.

Scenario 1: Testing a boolean condition

This is the simplest case:

if (condition) {}
else {}

Specifying a condition as else if would be redundant, and it's really obvious to the reader what the code does. There is no argument for using else if in this case.

Scenario 2: Testing for a subset of infinite states

Here we are interested in testing for conditions A and B (and so on), and we may or may not be interested in what happens if none of them holds:

if (conditionA) {}
else if (conditionB) {}
else {} // this might be missing

The important point here is that there isn't a finite number of mutually-exclusive states, for example: conditionA might be $num % 2 == 0 and conditionB might be $num % 3 == 0.

I think it's natural and desirable to use a reasonable amount of branches here; if the branches become too many this might be an indication that some judicious use of OO design would result in great maintainability improvements.

Scenario 3: Testing for a subset of finite states

This is the middle ground between the first two cases: the number of states is finite but more than two. Testing for the values of an enum-like type is the archetypal example:

if ($var == CONSTANT_FOO) {}
else if ($var == CONSTANT_BAR) {} // either this,
else {} // or this might be missing

In such cases using a switch is probably better because it immediately communicates to the reader that the number of states is finite and gives a strong hint as to where a list of all possible states might be found (in this example, constants starting with CONSTANT_). My personal criteria is the number of states I 'm testing against: if it's only one (no else if) I 'll use an if; otherwise, a switch. In any case, I won't write an else if in this scenario.

Adding else as an empty catch-errors block

This is directly related to scenario #2 above. Unless the possible states are finite and known at compile time, you can't say that "in any other case" means that an error occurred. Seeing as in scenario #2 a switch would feel more natural, I feel that using else this way has a bad code smell.

Use a switch with a default branch instead. It will communicate your intent much more clearly:

switch($direction) {
    case 'up': break;
    case 'down': break;
    default: // put error handling here if you want
}

This might be a bit more verbose, but it's clear to the reader how the code is expected to function. In my opinion, an empty else block would look unnatural and puzzling here.

Jon
  • 428,835
  • 81
  • 738
  • 806
0

I try not to write else. Ever. In my experience, using else results in less readable logic, especially when if/elses are being nested.

For assigning a var to either true or false (or any other simple this-or-that value), I always use:

$varx = false;
if ($my_codition_here === true) {
   $varx = true; 
}

When I have a bigger chunk of logic that you might consider "belongs" in the if/else, I make sure to structure my code so that if the condition is met, the function terminates, usually by returning:

if ($my_codition_here === true) {
    // A reasonable amount of logic goes here
    return $the_result_up_untill_here;
}

// All logic that would have been "else" goes here.
return $the_result_up_untill_here;

As phihag mentioned; use a switch statement when you consider elseif.

And as Your Common Sense already said, there is no best practise, but there are good practises, and I think this is one.

Jasper Kennis
  • 3,225
  • 6
  • 41
  • 74
0

I sometimes do it like this. I'm not worried that "left" is interpreted as "down" because I always validate my input, in this case with preg_match('{^up|down$}', $direction). Inarguably a switch is more appropriate... but I dislike the verbose syntax.

if ($direction == "up")
    {
    // code goes here...
    }
else //if ($direction == "down")
    {
    // code goes here...
    }
Core Xii
  • 6,270
  • 4
  • 31
  • 42