PSA: often in code reviews I hear "let's avoid `It...
# dev
g
PSA: often in code reviews I hear "let's avoid `Iterables.getOnlyElement(xs)`" because the error message is inscrutable if there's not exactly one element. However, the cleanest alternative,
xs.get(0)
isn't great because it also has an inscrutable error if there's zero elements, and it silently ignores if there's more than one (which, presumably, is bad since the logic didn't account for there being more than one). So, a solution: we now have
CollectionUtils.getOnlyElement
, which works like:
Copy code
final Interval queryInterval = CollectionUtils.getOnlyElement(
        query.getQuerySegmentSpec().getIntervals(),
        xs -> new IAE("Should only have one interval, got[%s]", xs)
    );
Relatively succinct and has a nice error message.
👍 5