Add iterables package containing helper method for getting the only element in a collection#520
Add iterables package containing helper method for getting the only element in a collection#520
Conversation
Generate changelog in
|
|
Tested this locally and was able to pull the new package in to a different repo and use |
carterkozak
left a comment
There was a problem hiding this comment.
I'd prefer not to duplicate guava functionality for safe logging, especially methods which don't take diagnostic message information. What if we provided a javaagent or similar to substitute our own implementation of the iterables/collections/etc methods which throw safe exceptions on failure, however don't require every developer to be aware of another utility class?
I worry that we're building too large a library of utility functionality that it becomes distracting and difficult to develop new components.
| import com.google.common.collect.Iterators; | ||
| ... | ||
| Preconditions.checkState(collection.size() == 1, "Expected exactly one element in collection", args); | ||
| return Iterators.getOnlyElement(collection.iterator()); |
|
|
||
| private Iterables() {} | ||
|
|
||
| public static <T, C extends Collection<T>> T getOnlyElement(C collection, Arg<?>... args) { |
There was a problem hiding this comment.
That's a collection, not an iterable. Guava Iterables takes an iterable, and iterators takes an iterator.
There was a problem hiding this comment.
Yeah looks like i mixed the two together -- I'd be happy to implement this for both Iterables and Iterators
|
That sounds like a good idea, although I haven't written a java agent before, any chance you can point me to one and I can give it a shot? I can implement this to substitute both Iterables and Iterators |
|
I can take a look at implementing this, although I can't promise a delivery date. |
|
up to you -- i'd be happy to take a stab at it but not having any luck in finding an example of us doing this for something similar |
Before this PR
We would have to call
Iterators.getOnlyElement(collection.iterator());directly whenever we wanted this functionality, having to also checkPreconditions.checkState(collection.size() == 1);before to make sure we would get a more sensible error message. I found myself having to use this a lot.After this PR
Now one can simply call
com.palantir.logsafe.Iterables.getOnlyElement(...)with their collection and can expect this to check that there is indeed 1 element in the collection before retrieving it, otherwise we fail with a nice error.