Java Minutiae - I love ternary
I love the? :
ternary operator. It makes my code feel tighter. Plus, I get to save code - fewer assignments, fewer return statements, and variable declarations are inline. In the code I was writing yesterday, a duplicated call to 'add()' made me itch for the ternary: for (String key : keys) {
if (getCardinality(key) == 1) {
singleValuedKeys.add(key);
} else {
multiValuedKeys.add(key);
}
}
Unfortunately, with standard use of a ternary, the code gets bigger instead of smaller:
for (String key : keys) {
Set<String> setToAddTo = (getCardinality(key) == 1)
? singleValuedKeys
: multiValuedKeys;
setToAddTo.add(key);
}
Taking it one-step further, I inline the
setToAddTo
variable. This is where the code loses its familiar feel: for (String key : keys) {
((getCardinality(key) == 1)
? singleValuedKeys
: multiValuedKeys).add(key);
}
It's tight, but somehow I've written Java code that doesn't have the Java feel. So I ended up dropping the ternary, and went with the familiar if/else structure. What's your preference?