Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the ternary operator more complex than if/else?

Tags:

php

pdepend

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.

like image 613
leyou Avatar asked Jun 13 '14 04:06

leyou


People also ask

Why ternary operator is better than if else?

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.

Is it better to use ternary operator or if else?

Conclusion. Use ternary operators to set a value to a variable, or to reduce code if necessary. Use if-else statements for everything else.

What is the advantage of ternary operator?

Advantages of Ternary OperatorIt will shorten the code. It will improve the readability of the code.

Is ternary operator faster than if in C?

It is not faster. There is one difference when you can initialize a constant variable depending on some expression: const int x = (a<b) ?


2 Answers

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.

like image 163
Matt Zera Avatar answered Oct 24 '22 04:10

Matt Zera


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

like image 20
Mark Miller Avatar answered Oct 24 '22 05:10

Mark Miller