valid8j
is a library that provides consistent programming experiences across DbC[1], Value-checking, and Test assertions.
It is named after valid4j
[2], but it does more.
It also provides readability both in codes and messages on failures. Easy to write.
IntroductionExample
classpublic class IntroductionExample {
public String examplePublicMethod(String name, int basePrice) {
// Use `Expectations.requireXyz` method to check values in production.
requireArguments(
that(name).satisfies()
.notNull(),
that(basePrice).satisfies()
.greaterThanOrEqualTo(0)
.lessThan(10_000));
return examplePrivateMethod(name, basePrice);
}
private String examplePrivateMethod(String name, int basePrice) {
// Use `assert` statement with`Expectations.` {`precondition`,`invariant`,`postcondition`} methods
// and their plural for Design by Contract programming.
assert preconditions(
// `value(var)` and `that(var)` are synonyms. Use the one you like.
// `toBe(var)` and `satisfies(var)` are synonyms. Use the one you like.
value(name).toBe()
.notNull(),
value(basePrice).toBe()
.greaterThanOrEqualTo(0)
.lessThan(10_000));
int price = (int) (basePrice * 1.08);
return String.format("%s:%s", name, price);
}
@TestMethodExpectation(FAILURE)
@Test
public void exampleMethod() {
String message = examplePublicMethod("Kirin Ichiban", 100);
// Use `Expectations.assertAll` for test assertions.
assertAll(
that(message)
.substringAfter(":")
.parseInt()
.satisfies()
.equalTo(110),
that(message)
.satisfies()
.startingWith("Kirin Ichiban"));
}
}
This gives the following output as your IDE’s window.:
IntroductionExample.java
Expectation | Actual |
---|---|
"Kirin Ichiban:108"->WHEN:transform ->true -> substringAfter[:] ->"108" "108" -> parseInt ->108 [0] 108 -> THEN:=[110] ->true "Kirin Ichiban:108"->WHEN:startsWith[Kirin Ichiban]->true .Detail of failure [0] --- =[110] --- |
"Kirin Ichiban:108"->WHEN:transform ->false -> substringAfter[:] ->"108" "108" -> parseInt ->108 [0] 108 -> THEN:=[110] ->false "Kirin Ichiban:108"->WHEN:startsWith[Kirin Ichiban]->true .Detail of failure [0] --- 108 --- |
Have a following maven dependency in your pom.xml
.
<dependency>
<groupId>com.github.dakusui</groupId>
<artifactId>valid8j</artifactId>
<version>{valid8j}</version>
</dependency>
Visit oss.sonatype.org to figure out the most recent version of valid8j
.
Check valid8j's documentation site for more detail.
-
[1] Wikipedia article on Design by Contract, https://en.wikipedia.org/wiki/Design_by_contract
-
[2] Valid4j, http://www.valid4j.org