2

我一直想知道这个速记,如果我们可以这样称呼它,是否是专业 PHP 开发人员公认的编码实践:

foo() && bar();

代替

if( foo() ) {
    bar();
}

虽然 IMO 单行代码更简洁,但我还没有看到它在任何地方使用。

4

4 回答 4

3

这是多种语言开发人员的常见做法。从技术上讲,它没有任何问题,但从它在 StackOverflow 上出现的次数来看,我会继续说它是“仅在唯一有意义的情况下使用”。大多数人都没有预料到。

也就是说,这是完全有效的:

foo()?bar()?bat():zonk():baz();

原样

foo() && bar() && baz();

只要记住:

function foo(){return true;} 
function bar(){echo "bar";} 
function baz(){echo "baz";  return 2;} 
echo foo()||foo()?baz():baz(); // baz2
于 2011-08-06T12:33:41.153 回答
1

就个人而言,我认为它没有任何问题。它相当普遍,因此大多数 PHP 程序员会像理解扩展版本一样理解它,因此完全可以接受。

于 2011-08-06T12:24:27.823 回答
1

The most important part is that you write code that is easy to read. Using function names like foo() and bar() for example are totally useless, so it's hard to say which one of the two you want to compare are better.

Next to that, the if example has some considerable flaws as well:

  • if is a language construct, but you use it like a function.
  • you add vertical space into the if condition. This can make things hard to read as spaces are influencing the visual focus.

An alternative suggestion would be:

if (foo()) {

But you wanted to compare the two: Code is always in it's context. And readable code uses it's context. Both of your suggestions can be valid, the key point is that you can read the meaning from the code already:

   conditionMet() && gotForIt();

   if (conditionMet()) goForIt();

Decide for yourself. Just don't mix from one line to the other, so keep one style through your whole code.

于 2011-08-06T12:45:36.753 回答
1

foo() && bar(); is a boolean expression, so it's wrong if you don't put it inside a boolean context (a condition like if, while, etc).

The code has to tell "the story" of the problem being solved, using this shortcut is not telling the story. It's an ugly hack, it's not elegant.

If you think about it as "neat", then you haven't yet reached the point where code means ideas, not code.

于 2011-08-06T12:49:01.670 回答