构造条件逻辑的最佳方法是什么?

Rup*_*ott 4 php formatting conditional

在我看来,有许多不同的方法来构造条件逻辑.据我所看到的,只要我们设置错误结束脚本(或者你能想象同样的例子,但在函数返回),那么下面的例子是相等的:

例1

if($condition1) {
    trigger_error("The script is now terminated");
    }

if($condition2) {
    trigger_error("The script is now terminated");
    }

echo "If either condition was true, we won't see this printed";
Run Code Online (Sandbox Code Playgroud)

例2

if(!$condition1) {
    if(!$condition2) {
        echo "If either condition was true, we won't see this printed";
        }
    else {
        trigger_error("The script is now terminated");
        }
    }
else {
    trigger_error("The script is now terminated");
    }
Run Code Online (Sandbox Code Playgroud)

例3

if($condition1) {
    trigger_error("The script is now terminated");
    }
else {
    if($condition2) {
        trigger_error("The script is now terminated");
        }
    else {
        echo "If either condition was true, we won't see this printed";
        }
    }
Run Code Online (Sandbox Code Playgroud)

例4 - 改编自弗雷泽的答案

function test($condition) { 
    if($condition) {
        trigger_error("The script is now terminated");
        }   
    }

test($condition1);

test($condition2);

echo "If either condition was true, we won't see this printed";
Run Code Online (Sandbox Code Playgroud)

就个人而言,我倾向于编写代码,如例1所示.这是因为我觉得通过检查以这种方式结束脚本(或函数)的条件,我可以清楚地定义脚本执行和未执行的内容,即条件之前的所有内容已经执行了,行后的一切都没有.这意味着当我在第147行收到错误时,我立即知道发生了什么事情,帮助我更快地找到错误.此外,如果我突然意识到我需要在$ condition1之前测试$ condition2,我可以通过简单的复制粘贴进行更改.

我看到很多代码都像例2中那样编写,但对我来说,调试看起来要复杂得多.这是因为,当嵌套变得太大时,错误将在底部的某条远线处被触发,并与由大量嵌套代码引起它的条件分开.另外,改变条件序列可能会更加混乱.

你可以混合使用两种样式,例如在例3中,但这似乎使事情过于复杂,因为所有的'其他'本质上都是多余的.

我错过了什么吗?构建条件代码的最佳方法是什么?有比这些例子更好的方法吗?是否存在一种风格可能优于另一种风格的具体情况?

编辑:示例4看起来很有趣,并不是我考虑过的事情.您还可以传递错误消息作为第二个参数.

谢谢!

PS请记住,我可能需要在检查$ condition1和$ condition2之间执行一些任意步骤,因此任何替代方案都必须适应.否则,有一些更好的替代方案,例如if($ condition1 || $ condition2).

Joh*_*ica 8

我在示例1阵营.根据经验,所需的压痕越少越好.

// Exit early if there are errors.
if ($n < 0) {
    die "bad n: $n";
}

// Handle trivial cases without fuss.
if ($n == 0) {
    return 0;
}

/* Now the meat of the function. */
$widget->frob($n);
foreach ($widget->blaxes as $blax) {
    checkFrobbingStatus($blax);
}
// ...And another 20 lines of code.
Run Code Online (Sandbox Code Playgroud)

当您使用if/else并将成功和错误代码放在并行部分中时,您会看起来好像两个代码块相同.实际上,应该不再强调边缘情况和错误条件.通过故意有意地处理错误,然后将"重要"代码放在else子句中,我觉得这样可以在视觉上更清晰地显示重要代码.

"这里有所有先决条件.现在这里是好东西."