Ternary operators in Java can make code unreadable

[nz_btn text="Cost" link="http://casthighlight.wpengine.com/category/product/indicators-methodology/cost/" icon="icon-office" color="green" shape="rounded" hover_normal="opacity"][nz_btn text="Software Agility" link="http://casthighlight.wpengine.com/software-resiliency/" icon="icon-dashboard" color="black" size="medium" shape="rounded"][nz_btn text="Code Readability" link="http://casthighlight.wpengine.com/category/product/indicators-methodology/code-insights/software-resiliency/code-reliability/" icon="icon-code" color="black" shape="rounded" type="ghost" hover_ghost="screen"]

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
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.
[nz_btn text="Cost" link="http://casthighlight.wpengine.com/category/product/indicators-methodology/innovation/" icon="icon-office" color="green" shape="rounded" hover_normal="opacity"]

CAST recommendations

References

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.
[nz_btn text="See features" link="http://casthighlight.wpengine.com/outputs-analytics/" icon="icon-stats" color="black" shape="rounded"][nz_btn text="How it works" link="http://casthighlight.wpengine.com/how-it-works/" icon="icon-cog" color="black" shape="rounded" type="ghost"] c
For reference only. For the complete details please refer the original article
https://doc.casthighlight.com/alt_ternaryoperators-avoid-ternary-operators-java/
Have more questions? Submit a request

Comments

Powered by Zendesk