I'm testing my libraries with pdepend and some functions have incredibly high complexity. I just realized it comes from the ternary operator, but I'm not sure why.
With a function like:
function test($a) {
return $a > 10 ? 5:20;
}
pdepend returns a complexity (npath) of 5. Why 5 different paths? I see only 2.
With a function like:
function test($a) {
if($a > 10)
return 5;
else
return 20;
}
The npath complexity is 2. Which makes sense.
Edit: Ok I had a look at the other question: PMD - NPath complexity very high with ternary operator (?
It's part of the algorithm.. Still, the function has only 2 possible paths. The algorithm doesn't make sense to me. The number of nodes do not reflect the number of paths, and it arbitrarily adds 2 to the value.
Emphasis: value-selection before/after action needing values. There's a different emphasis: An if / else statement emphasises the branching first and what's to be done is secondary, while a ternary operator emphasises what's to be done over the selection of the values to do it with.
Conclusion. Use ternary operators to set a value to a variable, or to reduce code if necessary. Use if-else statements for everything else.
Advantages of Ternary OperatorIt will shorten the code. It will improve the readability of the code.
It is not faster. There is one difference when you can initialize a constant variable depending on some expression: const int x = (a<b) ?
The algorithm that pdepend uses to determine complexity adds two for the use of the ternary operator even though they should be the same because it works the same as an if else and adds the same number of paths. From my experience you shouldn't see much of an actual difference if any in actual application.
The ternary operator makes a copy of non-object values. Meaning, in your first code sample, $a
is copied then the result is returned. Source. In the second code sample, no such copy is made.
My assumption, then, is that the extra paths involved come from making the copy.
Other resources to look at:
http://fabien.potencier.org/article/48/the-php-ternary-operator-fast-or-not
https://drupal.org/node/1838368
http://www.mail-archive.com/[email protected]/msg51926.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With