valid8j
is a library that provides consistent programming experiences across DbC, Value-checking, and Test assertions.
It also provides readability both in codes and messages on failures.
Easy to write.
IntroductionExample
classpublic class IntroductionExample {
public String examplePublicPublicMethod(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 = examplePublicPublicMethod("Kirin Ichiban", 100);
// Use `Expectations.assertAll` for test assertions.
assertAll(
that(message)
.substringAfter(":")
.parseInt()
.satisfies()
.equalTo(110),
that(message)
.satisfies()
.not(v -> v.nullValue())
.startingWith("Kirin Ichiban"));
}
}
This gives the following output as your IDE’s window.:
Expectation | Actual |
---|---|
"Kirin Ichiban:108"->WHEN:transform ->true -> substringAfter[:] ->"108" "108" -> parseInt ->108 [0] 108 -> THEN:=[110] ->true "Kirin Ichiban:108"->WHEN:allOf ->true -> not:isNull ->true -> 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:allOf ->true -> not:isNull ->true -> startsWith[Kirin Ichiban] ->true .Detail of failure [0] --- 108 --- |
Programmers who use this library at the first time, please check "Getting Started".
To know more about valid8j
for better usage, "Guides and Tutorials" and "API References" will be useful.
To contribute the valid8j
project, please also check the "Development" and "Architecture, Design Principles, and Techniques"
In case you have a trouble, please check "Limitation and Future Works" and "FAQs"
References
-
[1] Wikipedia article on Design by Contract, Design by contract
-
[2] valid4j valid4j.org
-
[3] pcond dakusui.github.io/pcond
-
[4] Valid4j, valid4j.org
-
[5] PreconditionsExplained, PreconditionsExplained
-
[6] Hamcrest hamcrest.org
-
[7] Programming With Assertions Programming With Assertions
-
[8] Preconditions, Google Guava Preconditions class
-
[9] Validates, Apache Commons Validate class