Sherlock
Sherlock

Reputation: 7597

Is this an acceptable use case of the ternary operator?

I was using the ternary operator to perform a very simple, conditional action. It worked well, but my IDE (PHPStorm) reported it as an error. The error I got was:

'void' method 'performAction' result used

The code I was using is this:

($this->doThis ? $class->performAction() : $class->performDifferentAction());

The error in PHPStorm is obviously wrong; I'm not using the result of the void method anywhere. I'm just calling the methods and that works as expected. I just used the ternary operator as a short-hand for this:

if($this->doThis)
{
    $class->performAction();
}
else
{
    $class->performDifferentAction();
}

I think this looks like a valid use case for the ternary operator. It's not obfuscated, easy to read and short.

Is this a design flaw nevertheless?

Upvotes: 0

Views: 105

Answers (1)

deceze
deceze

Reputation: 522125

The ternary operator is an expression which returns a result. Its purpose is to be used when an "inline condition" is needed which would otherwise require you to create one or two additional variables. As such, whenever you use a ternary operator, you're kind of expected to use its result.

For example, you wouldn't write this, would you?

1 + 2;  // result not used, does nothing

What you're essentially doing there is write such code, but add a side effect to it:

1 + someFunc();  // soooo... does this do anything?

Your IDE therefore urges you to explicitly write side-effect code using if..else. It more directly expresses what you're doing there.

Having said all that, it's ultimately up to you and your style. PhpStorm has its preferences; if you want to override them, switch off that particular inspection. However, that inspection is there to help you write better code; it would warn you if you really forgot to assign a return value somewhere.

Upvotes: 3

Related Questions