Hacker News new | ask | show | jobs
by selfsimilar 3406 days ago
In PHP I like using Yoda Conditions because there's a common idiom of testing assignment in the conditional:

    if ($value = getSomeValue()) {
      // Safely use value
    }
Yoda Conditions defend nicely against accidents when '=' and '==' can be used legally this way and honestly you get used to reading them pretty quick.
3 comments

Just wrap the condition inside another pair of parentheses; that should get any linter off your back without needing to deal with the annoying flipped conditions – and if someone doesn't know the code base has a 100% coverage of Yoda conditions, they might just think there's a bug on the line when seeing it for the first time (unless you add an explanatory comment each time, at which point the assignment inside the condition has bought you nothing, as you might just lift it on a row of its own before the if statement).

C++, for instance however has language syntax to prevent confusion when using this idiom – declarations inside conditionals:

  if (auto val = getval())
    foo(val); // executed only if getval() returned something that evaluates to true
              // in a boolean context
Considering that PHP already has the useless var keyword, they might just adopt something similar in the future

  if (var $val = getval()) {}
I've been coding for decades and I still find them jarring.

They're also a false sense of security as they won't catch:

    if $(value = $someOthervalue) ...
I don't see at all how you could call this a Yoda Condition: it couldn't be written any other way, as it would cause a syntax error.