结束if ... else语句的最佳做法,不带条件

Joh*_*zen 10 php if-statement coding-style

在没有else条件的情况下结束if ... else语句的最佳做法是什么?请考虑以下代码:

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

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

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

else {
  //do nothing?
}
Run Code Online (Sandbox Code Playgroud)

如你所见,只有两个条件; 向上或向下并且else语句实际上没有用处,除非您希望它显示错误消息.

大多数时候,我看到程序员只是将else条件放在那里但插入注释而不是像这样的任何工作代码.

else {
      //error messages goes here...
}
Run Code Online (Sandbox Code Playgroud)

或者只是假设它不是"向上",那么其他一切都应该"向下",因为只有2个条件.如果用户输入"左"或"右",它仍将被视为"向下".我认为这有点不合适.

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

else {
  code goes here...
}
Run Code Online (Sandbox Code Playgroud)

我知道如果我们在没有其他条件的情况下放置PHP,PHP仍然可以工作.但是如果有一个elseif条件怎么办?在这样的情况下,如果我们想要保留严格的if ... else语句,如果我们不想包含任何错误消息或有任何其他条件,那么最佳做法是什么?

提前致谢.

You*_*nse 21

没有if...else声明.
if声明可以扩展elseelseif运营商.

因此,if无条件语句的最佳实践elseif无条件语句else:

if (condition) {
  //some code
}
Run Code Online (Sandbox Code Playgroud)

坦率地说,没有if...else.最佳实践只是遵循程序逻辑的实践.
就这样

  • 我认为这是一个笼统的答案,没有抓住重点。 (2认同)

phi*_*hag 7

不写空else.这只会使代码混乱,而且你的意思非常明显.

在许多情况下,您实际上可以使用switch语句:

switch ($_POST['direction') {
case 'up':
     // code ...
     break;
case 'down':
     // code ...
     break;
default: // else
     throw new Exception('Invalid direction value');
}
Run Code Online (Sandbox Code Playgroud)