Loading...

Redundant conditional expression with the ternary operator

:heavy_exclamation_mark: This post is older than a year. Consider some information might not be accurate anymore. :heavy_exclamation_mark:

This operator (?) is also known as the ternary operator because it uses three operands. Instead of an if-then-else statement this operator can make your code more readable, when something is so simple you don’t want to waste many lines for.

I have stumbled recently over this code in a stackoverflow post:

String str = "Y";//or else "N"
boolean isManager = (str.equals("Y")) ? true : false;

Critical points from my point of view:

  • parenthesis is unnecessary
  • a control flow issue, since str.equals("Y") already returns true or false, the use of the ternary operator is redundant

Clean code

String str = "Y";//or else "N"
boolean isManager = str.equals("Y");
Please remember the terms for blog comments.