patternjavaCritical
Ternary operation in Java - isn't this abuse?
Viewed 0 times
thisjavaoperationabuseternaryisn
Problem
I think the below code is difficult to understand. I also feel it abuses Java's ternary operator.
Above
I'd prefer something instead of such a nested ternary operator, if it looks cleaner and easier to understand. It would also be easy to sort out merge issue in, say, SVN.
N.B: There are even more nested ternary conditions in the code that I just have taken over.
Is there any general guideline which suggests the number of levels a ternary operator should be allowed? In other words, any guideline suggesting when you should break your ternary operator for better code readability?
String name = ((this.getAllNamesAsDelimitedString().contains(incomingName) ?
incomingName:
(CollectionsUtils.isEmptyCollection(this.getEntityOperationMap()) ?
null :
this.getEntityOperationMap.get(incomingName))));Above
getAllNamesAsDelimitedString will return a comma (,) delimited String.I'd prefer something instead of such a nested ternary operator, if it looks cleaner and easier to understand. It would also be easy to sort out merge issue in, say, SVN.
N.B: There are even more nested ternary conditions in the code that I just have taken over.
Is there any general guideline which suggests the number of levels a ternary operator should be allowed? In other words, any guideline suggesting when you should break your ternary operator for better code readability?
Solution
I think it's important to note that nested ternary operators can be formatted to look good:
This isn't the most readable option in your case, because you have longer method calls, but I think it's better when the conditions are kept short and meaningful.
String name = isConditionA ? "first"
: isConditionB ? "second"
: isConditionC ? "third"
: "fourth";This isn't the most readable option in your case, because you have longer method calls, but I think it's better when the conditions are kept short and meaningful.
Code Snippets
String name = isConditionA ? "first"
: isConditionB ? "second"
: isConditionC ? "third"
: "fourth";Context
StackExchange Code Review Q#6544, answer score: 57
Revisions (0)
No revisions yet.