开发者

Best practice on ending if...else statement without else condition

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 g开发者_如何转开发oes 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.


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


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');
}


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.


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.


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...
    }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜