Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 950
John Citizen Avatar asked Mar 15 '11 15:03

John Citizen


People also ask

Can you end an if statement without an else?

Answer 526897a4abf821c5f4002967 An if statement looks at any and every thing in the parentheses and if true, executes block of code that follows. If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.

Is else mandatory after ELSE IF?

So I hope not tl;dr the first questions answer is no, a else can follow after an if but it does not need to, the other way is completely prohibited (else without if), makes sense as this would mean do it in all cases, where you would not need a condition, so it is expected to be an unwanted error.


1 Answers

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');
}
like image 197
phihag Avatar answered Sep 19 '22 16:09

phihag