DEFENSIVE PROGRAMMING WITH KLOJANG CHECK
Basic Usage
The Check class is the central class of the Klojang Check module. All checks start out from there. It is a factory class for two types of check objects:
- IntCheck — for validating int values
- ObjectCheck<T> — for validating values of type T
Taking the code example from the Introduction again:
public class InteriorDesigner {
private final int numChairs;
public InteriorDesigner(int numChairs) {
this.numChairs = Check.that(numChairs).is(gte(), 0).is(lte(), 4).is(even()).ok();
}
public void applyColors(List<Color> colors) {
Check.that(colors).is(notEmpty().and(contains(), noneOf(), RED, BLUE, PINK);
// apply the colors
}
public void addCouch(Couch couch) {
Check.notNull(couch).isNot(c -> c.isExpensive(), "couch too expensive");
// add the couch
}
}
numChairs is an int value, so Check.that() produces an IntCheck. This gives you access to the int-specific checks from the CommonChecks class – in this case the gte(), lte() and even() checks. The code example doesn't show it, but these are static imports from the CommonChecks class. colors is a List, so Check.that() produces an ObjectCheck that lets you access the Collection- and List-specific checks, like the contains() check. couch is, well, a Couch. There are no Couch-specific checks in the CommonChecks class, but you can still provide your own lambdas and method references that test the Couch instance.
By default, if a value fails to pass any of the tests following Check.that(), an IllegalArgumentException is thrown, but this can be customized. See the chapter on Exceptions.