DEFENSIVE PROGRAMMING WITH KLOJANG CHECK

Introduction

Welcome to Klojang Check.

Klojang Check is a Java module dedicated to defensive programming. It lets you specify checks on program input, object state and method arguments in a concise and elegant manner. Its conciseness might even make you want to use it for sanity checks on program elements not usually associated with precondition validation — local variables, for example.

In addition, Klojang Check comes with a well-curated set of common checks on values of various types. These checks are associated with short, informative error messages, so you don't have to invent them yourselves.

Klojang Check's take on pre- and postcondition validation is different from, for example, Guava's Preconditions class and Apache's Validate class. Below is an example of what precondition validation looks like with Klojang Check. The following chapters will explain what exactly is going on, but you will likely get the gist of it.

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
  }

}