DEFENSIVE PROGRAMMING WITH KLOJANG CHECK

Returning the Validated Value

Once the value under scrutiny has passed all tests, you can return it using the ok() method on IntCheck and ObjectCheck:

    this.numChairs = Check.that(numChairs).is(positive()).is(lt(), 5).is(even()).ok();

You can optionally pass a transformation function to the ok() method to make the value fit the assignment target:

    Car car = Check.notNull(vehicle).is(instanceOf(), Car.class).ok(Class::cast);

Alternatively, if there isn't much left to do with the value you can pass it to a simple Consumer using the then() method:

    List<String> words = ...;
    Check.that(word).is(keyIn(), dictionary).then(words::add);

Even at this late stage it is still possible to decide the value is not valid after all. Both the transformation function and the consumer are allowed to throw a checked exception. These are the method signatures for the ok() and then() methods:

  // ObjectCheck:
  public <R, X2 extends Throwable> R ok(FallibleFunction<T, R, X2> transformer) throws X2
  public <X2 extends Throwable> void then(FallibleConsumer<T, X2> consumer) throws X2

  // IntCheck:
  public <X2 extends Throwable> int ok(FallibleIntUnaryOperator<X2> transformer) throws X2
  public <X2 extends Throwable> void then(FallibleIntConsumer<X2> consumer) throws X2

The "fallible" functions reside in the org.klojang.check.fallible package and are the exception-throwing counterparts to their almost-namesakes in the java.util.function package. The JDK may not have included this type of functional interfaces because they don't sit well with (multithreaded) stream processing, but that is obviously not what we are doing and they do come in handy here.