Ternary operators in Java can make code unreadable

CostSoftware AgilityCode Readability

Ternary operators in Java can make code unreadable

This code insight counts one violation each time a ternary operator is encountered.

Note : Do not confuse with question mark used as wildcard for unknow generic type.


String data = (str.contains("A") ? "Str contains 'A'" : "Str doesn't contains 'A'");


if (str.contains("A")) {
    data = "Str contains 'A'";
else {
     data = "Str doesn't contains 'A'";


Why you should care

While the ternary operator is pleasingly compact, its use can make code more difficult to read. It should therefore be avoided in favor of the more verbose if/elsestructure.

Business Impacts

It is recommended to avoid these in order to ensure the code is more readable and cost effective.


CAST recommendations



About CAST and Highlight’s Code Insights

Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.

See featuresHow it works