Peter Stuifzand

Ternary operator

The ternary operator can be found in many programming languages. In some popular ones it is written as bool ? expr1 : expr2, which will evaluate to expr1 if bool is true or expr2 if bool is false.

The nice thing about the ternary operator is that one can write an otherwise big if block in one line. For example:

$var = null;
if ($x > 10) {
    $var = 102;
}
else {
    $var = 1044;
}

becomes

$var = $x > 10 ? 102 : 1044;

I hope it’s obvious what the pros are of this approach.

But then I read an article which tries to explain the usage of the ternary operator in Java. At first I liked the simple design of the page. But the code examples are probably some of the worst that I have seen.

boolean giveTicket;
giveTicket = speed > speedLimit ? true : false;
if (giveTicket)
    pullEmOver();   // nab the offender!

The biggest problem with this example is that second and third part of the expression are true and false. The first part of the expression itself will already evaluate to that, so that’s redundant. This example can be written without the ternary operator.

if (speed > speedLimit) {
    pullEmOver();
}

This is cleaner and contains less words. To have the same obvious code, you could create a method for that comparison.

public boolean giveTicket(int speed) {
        return speed > speedLimit;
}

...

if (giveTicket(speed)) {
    pullEmOver();
}

It won’t get better than this. The nice thing about this is that you can change the code in giveTicket if there are changes to the ideas about what is illegal.

© 2023 Peter Stuifzand