ariya.io About Talks Articles

Ternary Conditional and Boolean Values

1 min read

Many programming languages support the ternary conditional operator. It is very useful to shorten the code since something like:

if (fast)
  speed = 70;
else
  speed = 25;

can be rewritten to look like the following (C-style syntax). In such a form, it is also concise, readable, and unambiguous.

speed = fast ? 70 : 25;

Chaining or cascading ternary conditions is also a common practice although it is not always recommended, especially if it is more than two operations.

A few times I’ve seen code written by experienced programmers that mixes the ternary operator with Boolean values in a weird way:

young = (age < 18) ? true: false;

This is quite baffling since technically what you need to write is only:

young = (age < 18);

Another variant of such a redundancy is something resembling:

speed = (warp == true) ? 2.5 : 0.3;

There are different theories as to why this scenario occurs. The most obvious reason is of course an oversight, a simple honest mistake. Another explanation is that originally the said line of code did not deal with Boolean values, perhaps some constants or enums, and then got refactored incompletely, leaving the nonchalant historical structure.

Have you spotted a similar situation? How did it happen?

Related posts:

♡ this article? Explore more articles and follow me Twitter.

Share this on Twitter Facebook