php 在没有 else 条件的情况下结束 if...else 语句的最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5313706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:58:14  来源:igfitidea点击:

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

phpcoding-styleif-statement

提问by John Citizen

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

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

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

如您所见,只有 2 个条件;无论是向上还是向下,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 条件放在那里,但插入了一条注释,而不是像这样的任何工作代码。

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.

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

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?

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

Thanks in advance.

提前致谢。

回答by Your Common Sense

There is no if...elsestatement.
There is only an ifstatement that can be extended with elseand elseifoperators.

没有if...else声明。
只有一个if语句可以用elseandelseif运算符进行扩展。

So, the best practice on ifstatement without elsecondition is an ifstatement without an elsecondition:

因此,在最佳实践if,而不声明else的条件是if没有声明else的条件:

if (condition) {
  //some code
}

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

坦率地说,没有最佳实践。最佳实践只是遵循程序逻辑的一种。
就这样

回答by phihag

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

不要写空elses。这只会使代码混乱,而且您的意思很明显。

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

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

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

回答by Jon

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

场景 1:测试布尔条件

This is the simplest case:

这是最简单的情况:

if (condition) {}
else {}

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

指定一个条件else if是多余的,而且代码的作用对读者来说非常明显。else if在这种情况下使用没有任何争论。

Scenario 2: Testing for a subset of infinite states

场景 2:测试无限状态的子集

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:

在这里,我们对测试条件 A 和 B(等等)感兴趣,我们可能对如果它们都不成立会发生什么感兴趣,也可能不感兴趣:

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: conditionAmight be $num % 2 == 0and conditionBmight be $num % 3 == 0.

这里的重点是没有有限数量的互斥状态,例如:conditionA可能是$num % 2 == 0conditionB可能是$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.

我认为在这里使用合理数量的分支是自然和可取的;如果分支变得太多,这可能表明明智地使用 OO 设计将导致极大的可维护性改进。

Scenario 3: Testing for a subset of finite states

场景 3:测试有限状态的子集

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 switchis 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 ifin this scenario.

在这种情况下,使用 aswitch可能更好,因为它会立即向读者传达状态的数量是有限的,并给出了关于在哪里可以找到所有可能状态的列表(在此示例中,常量以 开头CONSTANT_)的强烈提示。我的个人标准是我要测试的状态数:如果只有一个(否else if),我将使用if; 否则,一个switch。无论如何,我不会else if在这种情况下写一个。

Adding elseas an empty catch-errors block

添加else为空的 catch-error 块

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 switchwould feel more natural, I feel that using elsethis way has a bad code smell.

这与上面的场景#2 直接相关。除非可能的状态是有限的并且在编译时已知,否则您不能说“在任何其他情况下”意味着发生了错误。看到场景#2 aswitch会感觉更自然,我觉得使用else这种方式有一种糟糕的代码味道。

Use a switchwith a defaultbranch instead. It will communicate your intent much more clearly:

使用switch带有default分支的a代替。它将更清楚地传达您的意图:

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 elseblock would look unnatural and puzzling here.

这可能有点冗长,但读者很清楚代码的预期功能。在我看来,一个空else块在这里看起来不自然和令人费解。

回答by Core Xii

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 switchis more appropriate... but I dislike the verbose syntax.

我有时会这样做。我不担心这会"left"被解释为"down"因为我总是验证我的输入,在这种情况下使用preg_match('{^up|down$}', $direction). 无疑 aswitch更合适……但我不喜欢冗长的语法。

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

回答by binaryLV

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

我认为如果没有什么可做的else,那么else代码中就不需要存在块。如果else包含块,则意味着它有存在的目的,因此代码尚不完整,如果它为空。

回答by Jasper Kennis

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

我尽量不写else。曾经。根据我的经验,使用会else导致可读性降低,尤其是在嵌套 if/elses 时。

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

为了将 var 分配给trueor false(或任何其他简单的 this-or-that 值),我总是使用:

$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/else 中有一大块你可能认为“属于”的逻辑时,我确保构建我的代码,以便如果满足条件,函数将终止,通常通过返回:

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 switchstatement when you consider elseif.

正如 phihag 所提到的;switch考虑时使用语句elseif

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

正如你的常识已经说过的那样,没有最佳实践,但有好的实践,我认为这是一种。