Java Tip #9: Use CollectionUtils for evaluation and manipulation of Collections
After quite some time this is another instance of the Java Tips. It's an addition to the Apache Commons related framework tips which are guiding into the direction that as a developer you should take advantage of existing and proven frameworks and know their features to leverage your development efficiency. This time complexity of the given example is a bit higher than in the previous tips.
Advice
Use Apache CollectionUtils for evaluation and manipulation of Collections.
Code-Example
A short spoiler for the following code: This is a routine which checks a given set of categories against a set of category-permissions for a user. The result is a set of categories, which the user is allowed to access.
Before
...
public boolean hasPermissionsToAccessCategory(String category) {
return (this.permissions != null && this.permissions.contains(category));
}
...
...
public Set<String> getCategoriesAllowedToViewBySearchFilter() {
Set<String> result = null;
if ((this.filter != null && this.filter.getCategory() != null) && (!this.filter.getCategory().isEmpty())) {
result = new HashSet<String>();
for (String category : this.filter.getCategory()) {
if (this.hasPermissionsToAccessCategory(category)) {
result.add(category.toString());
}
}
if(result.size() == 0) {
result = null;
}
} else {
result = this.getAllCategories();
}
return result;
}
....
After
...
public Set<String> getCategoriesAllowedToViewBySearchFilter() {
Set<String> result = null;
if (this.filter != null &&
this.permissions != null &&
CollectionUtils.isNotEmpty(this.filter.getCategory())) {
// get only categories, which are both in permissions and filter categories
result = new HashSet<String>(CollectionUtils.intersection(this.permissions, this.filter.getCategory()));
// if no results, return null
if(result.isEmpty()) {
result = null;
}
} else {
result = this.getAllCategories();
}
return result;
}
...
Benefit
Huge readability gain and a safety gain. The code and intention is much clearer here and also has a smaller footprint. The maintainability has been raised because for a developer not familiar with the routine it needs a bit of brainpower to find out what the initial code really does. The removal of the additional method and usage of CollectionUtils.intersection() makes it much easier to understand, how the two sets are compared to each other to retrieve the correct results.
Remarks
None if you are initially writing similar logic. If you're refactoring a method which seems to be better off with framework-provided functionality be careful and think over it a second time. Re-evaluate the code until you're really sure because it's easy to overlook a small detail which changes the results for a certain special case.