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.

bad

String data = (str.contains(“A”) ? “Str contains ‘A'” : “Str doesn’t contains ‘A'”);

good

void process(List<? extends Foo> list) {…}

public static void printList(List<?> list) {
for (Object elem: list)
System.out.print(elem + ” “);
System.out.println();
}

5362

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.

Cost

CAST recommendations

References

5362

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

c