DEFENSIVE PROGRAMMING WITH KLOJANG CHECK

Validating Interrelated Values

Sometimes, an argument, field or variable cannot be tested in isolation. Its validity depends on the value of another argument, field or variable.

  public void getPresident(Election election) {
    Check.that(election.isRigged()).is(yes().or(election.getWinner(), EQ(), me));
    // get the president ...
  }

In this example the election only needs to be rigged if it turns out you lost it.

Again, as with the chapter on Value Domain Tests, notice that the or() method is called on a the yes() check. This is explained separately in the chapter on Composing Tests.

eq() or EQ()?

Klojang Check uses bash-style names for the comparison operators: eq(), ne(), lt(), lte(), gt() and gte(). The lowercase variants return an IntRelation. In other words, they are for comparing int values. The uppercase variants return an instance of <T extends Comparable<T>> Relation<T, T>. In other words, they will let you compare any two Comparable instances of the same type. Use them to compare types like Double, double (autoboxed to Double), LocalDate and String. Actually, EQ() is the one exception here: it just returns Object::equals.