I have two collections, and items that are added to one or the other of those collections based on whether some criteria is met.
Somewhat inadvertantly, I stumbled on the fact that it is legal to write
(test(foo) ? cOne : cTheOther).add(foo);
instead of
if (test(foo)) {
cOne.add(foo);
} else {
cTheOther.add(foo);
}
While the first makes me feel clever (always a plus), I'm not sure about longer term readability, maintainability, etc. The basic advantage I see is that if I know I'm always going to be doing the same thing, it becomes one location to change a method (instead of two, or perhaps many if I'm implementing a switch statement via conditional operators). The main disadvantage occurs when that becomes not the case (i.e., I need add a method call to some cases and not others).
What pros and cons of the two methods (or other solutions) do you see?
If you don't think this particular instance of using the conditional operator to set which object to call a method with is the right choice, are there cases where it is reasonable?