DEFENSIVE PROGRAMMING WITH KLOJANG CHECK

Validating Argument Properties

If the value to be validated is an object, its validity may to a large extent depend on the validity of its properties. Therefore, Klojang Check enables you to check argument properties as part of validating the argument. This is done via the has() and notHas() methods on IntCheck and ObjectCheck.  (IntCheck? Properties? Yes, see the red info box below.)

public class QueryExecutor {

  private final Query query;

  public QueryExecutor(Query query) {
    this.query = Check.that(query, "query")
        .has(Query::where, "where", notEmpty())
        .notHas(Query::offset, "offset", negative())
        .has(Query::limit, "limit", gte(), 10)
        .has(Query::limit, "limit", lte(), 100)
        .ok();
  }

}

If, in this example, a query would be passed with a limit of 500, an IllegalArgumentException would be thrown with the message:

query.limit must be <= 100 (was 500)

Note that the term "property" is somewhat misleading. This first argument to has() and notHas() simply is a function that takes the value being validated and produces some other value, which is then also validated. In that sense an int value also has properties — for example "its" absolute value or "its" cosine:

Check.that(-7).has(Math::abs, "absolute value", eq(), 7);
Check.that(30).has(Math::cos, "cosine", LTE(), .5);