当我偶然发现一个与此类似的构造时,我正在重构一些旧代码:
@H_301_30@// 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);
虽然它看起来很奇怪,但是它要短得多
$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();