DEFENSIVE PROGRAMMING WITH KLOJANG CHECK

Common Checks

While IntCheck and ObjectCheck provide a mould for you to "pour" your checks into, the actual validation happens inside those checks. Checks are provided in the form of lambdas and method references, or, if you wish, chosen from the CommonChecks class. The CommonChecks class is a grab bag of common checks on values of various types. Checks like lte() and even() are static imports from this class.

The advantage of using the checks from the CommonChecks class, if you can, is that they have been hooked up to ready-made error messages, so you don't have to invent them yourself. For example, the following two checks do exactly the same thing:

    Check.that("John Smith", "full name").is(hasSubstring(), "Peter");
    Check.that("John Smith", "full name").is(String::contains, "Peter");

However, these are the error messages you get, respectively:

full name must contain Peter (was John Smith)
invalid value for full name: no such relation between John Smith and Peter

What It Says On The Tin

Note that the checks from the CommonChecks class only test what they are documented to be testing. None of them do a preliminary null check — or any other preliminary sanity check for that matter. If the value to be tested could possibly be null, you should always start with the notNull() check. Otherwise an unprocessed NullPointerException can and will come your way. This is bad, because it doesn't mean that the code implementing the business logic is invalid, but rather the check that was meant to protect it.