Atom Feed SITE FEED   ADD TO GOOGLE READER

Coding in the small with Google Collections: Preconditions

Part 1 in a Series.

In this N-part series, I'll demonstrate my favourite APIs from the recently announced Google Collections project. I'll present before and after examples that show how you can use Google Collections to write more concise code.

Preconditions provides methods for state validation. It makes input validation compact enough that you'll always want to do it! And unlike Java's built-in assert, Preconditions is always enabled.

Before:

  public Delivery createDelivery(Order order, User deliveryPerson) {
if(order.getAddress() == null) {
throw new NullPointerException("order address");
}
if(!workSchedule.isOnDuty(deliveryPerson, order.getArrivalTime())) {
throw new IllegalArgumentException(
String.format("%s is not on duty for %s", deliveryPerson, order));
}

return new RealDelivery(order, deliveryPerson);
}


After:

  public Delivery createDelivery(Order order, User deliveryPerson) {
Preconditions.checkNotNull(order.getAddress(), "order address");
Preconditions.checkArgument(
workSchedule.isOnDuty(deliveryPerson, order.getArrivalTime()),
"%s is not on duty for %s", deliveryPerson, order);

return new RealDelivery(order, deliveryPerson);
}


In addition to a constraint check, Preconditions also works as programmer documentation. When the code is under maintenance, the original author's expectations are right in the code where they belong. As a special treat, Preconditions throws detailed error messages that include the offending line of code.

Part 2