1

In situations when we need to write something like this:

if ($doStuff) {
    $obj->doStuff();
}

is it acceptable to write something like this?

$doStuff && $obj->doStuff();

If not, why?

3
  • 3
    Subjective. Try to write code that's less clever and more readable. Think of reading code like reading a book. Most people would rather read code written like a children's book than a technical novel.
    – Alternatex
    Oct 4, 2016 at 13:53
  • 1
    Also, ask yourself why and when you would use this in JS.
    – Eiko
    Oct 4, 2016 at 14:04
  • I use it for initializing variables (array keys) and sometimes for simple and repetitive logic (string appending with many conditionals). I would avoid it for domain logic though - ifs require attention. Also I like it to be different from standard boolean operations, so I use and/or operators (visible in IDE).
    – shudder
    Oct 4, 2016 at 17:25

1 Answer 1

5

For me, it's not good practice.

First, it hides the logic. Everyone can easily see what the if-construction means. The other is just... "clever" coding, which you shouldn't do.

You can't reorder the two things, although generally, you should be able to (oh wait, there are side effects!).

The result of the expression is not used? Hmm... I might just delete that line of code.

Also, I don't think doing boolean operations with parameters that are maybe void/null/... is a good thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.