我正在重构一些旧代码时,偶然发现了一个类似于这样的结构:
// function bar() returns a value
// if the value is an instance of customException class, terminate with error code
// else process the regular data
$foo = bar();
checkForException($foo) && exit($foo->errorCode());
process($foo);
虽然看起来很奇怪,但这比之前的要短得多。
在IT技术方面。$foo=bar();
if(checkForException($foo)) {
exit($foo->errorCode();
}
else {
process($foo);
}
有些更易读(至少在最初的惊喜之后)
$foo=bar();
(checkForException($foo)) ? exit($foo->errorCode()) : process($foo);
虽然代码越短并不一定意味着可读性更高,但我发现这种方式处于上述两种“标准”方式的中间。
换句话说,与其使用
if($foo) {
bar();
}
else {
// there is no real reason for this to exist, since
// I have nothing to write here, but I want to conform
// to the general coding practices and my coding OCD
}
有时候我们可以直接编写以下代码:
$foo && bar();
那么为什么这种方法没有被广泛使用呢?可能只是因为“不要重复造轮子,写更易读的if/else语句,如果你真的想缩短代码,那就用三目运算符”这样简单吧。
编辑:请注意,上面的代码是从原始代码中快速派生出来的,只是用于说明“短路”代码的用法。如果可以,请不要建议代码改进,因为这不是问题的预期结果。
示例2
userCheckedTheBox($user) && displayAppropriateInfo();
exit
。此外,完整的if/else
允许您在else
分支中使用多个指令 - 但有时短路运算非常有用,只是不要滥用它。 - moonwave99throw-catch
块了。 - Elias Van Ootegem