结束if ... else语句无else条件的最佳实践 [英] Best practice on ending if...else statement without else condition

查看:262
本文介绍了结束if ... else语句无else条件的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结束没有else条件的if ... else语句的最佳实践是什么?请考虑以下代码:

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

正如你所看到的,无论是向上还是向下,并且else语句没有真正的目的,除非你要它显示一个错误消息。

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.

大多数时候,我看到程序员简单地把else条件,但插入注释,而不是像这样的任何工作代码。

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

或者假设它不是'up'应该是'down',因为只有2个条件。如果用户输入左或右,它仍将被认为是下。我认为这有点不恰当。

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

我知道PHP仍然可以工作,如果我们把if没有else条件。但是如果有一个elseif条件呢?在这样的情况下,如果我们想要保持严格if ... else语句,如果我们不想包括任何错误消息或有任何其他条件,最佳实践是什么?

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?

提前感谢。

推荐答案

没有 if ... else 语句。

如果语句可以扩展 else elseif 运算符。

there is no if...else statement.
there is if statement that can be extended with else and elseif operators.

所以,的最佳实践if 语句不含 else 条件为如果语句不含 else 条件:

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

if (condition) {
  //some code
}

坦率地说,没有最佳做法。最好的做法是遵循程序逻辑。

这就是

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

这篇关于结束if ... else语句无else条件的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆