Guava
Lists are your friend.
October 09, 2013Guava is a time saver. I was reviewing some code, and came across the following method:
protected List<Map<String, Object>[]> buildPages(List<Map<String, Object>> articles, Integer perPage) {
int index = 0;
Map<String,Object>[] page = null;
for (Map<String, Object> a : articles) {
if(index == 0) {
page = new Map[perPage];
pages.add(page);
}
page[index++] = a;
index %= perPage;
}
return pages;
}
This is a little hard to follow, but it is simply paginating a set of maps. I was confused by the use of index and page here, so I asked the developer whether it mattered if we had List<Map[]>
or List<List<Map>>
. It didn't, so this is the equivalent using Guava Lists:
protected List<List<Map<String, Object>>> buildPages(List<Map<String, Object>> articles, Integer perPage) {
return Lists.partition(articles, perPage);
}
So there's some really cool points about this:
- Guava again anticipates a common pattern gracefully.
- Since we're now using a list, it's not possible to have null values in the collection
- This negates a category of errors and defensive patterns (null checking)
I'm also not a fan of the new array syntax in 7. new Map[perPage]
is confusing because it's a constructor to an array with the size in what is normally the 'address' segment. The shortcut of new List<>();
isn't adding any clarity either.
Addendum
I just wanted to add that I don't think original code above is bad; it is actually completely correct. The shift of type from array to a list of lists is the important thing here. If you can think in terms of the types and what they mean, they can open up some really interesting solutions. Guava exposes this discipline well with its Lists and Collections, etc. classes. They are really good tools especially in the way they instruct you on how to use them. More in the wiki