A fluent API for enforcing design contracts with automatic message generation:
✔️ Easy to use
✔️ Fast
✔️ Production-ready
To get started, add this Maven dependency:
<dependency>
<groupId>com.github.cowwoc.requirements</groupId>
<artifactId>java</artifactId>
<version>8.0.10</version>
</dependency>
and this Maven plugin:
<plugin>
<groupId>com.github.cowwoc.requirements</groupId>
<artifactId>maven_plugin</artifactId>
<version>8.0.10</version>
<executions>
<execution>
<goals>
<!-- Generate API classes -->
<goal>generate-api</goal>
<!-- Optional: enable colored diffs -->
<goal>unpack</goal>
</goals>
</execution>
</executions>
</plugin>
The contents of the API classes depend on which modules are enabled.
import static com.github.cowwoc.requirements.DefaultRequirements.requireThat;
public final class Credentials
{
public Credentials(String username, String password)
{
this.username = requireThat(username, "username").isTrimmed().isNotEmpty().getActual();
this.password = requireThat(password, "password").isTrimmed().length().isBetween(18, 30).getActual();
}
}
Failures would trigger the following kind of exceptions:
java.lang.NullPointerException: username may not be null
java.lang.IllegalArgumentException: password may not contain leading or trailing whitespace.
Actual: " Dumbl4dor4 "
java.lang.IllegalArgumentException: password must contain [18, 30) characters.
Actual: 15
- Automatic message generation
- Diffs provided whenever possible
- Clean stack-traces
- Assertion support
- Multiple validation errors
- Grouping nested requirements
- String diff
- Fast... very fast!
The best way to learn about the API is using your IDE's auto-complete engine. There are seven entry points you can navigate from:
The API has 7 entry points:
- requireThat(value, name)
- validateThat(value, name)
- assertThat(Consumer)
- assertThatAndReturn(Function)
- Requirements
- GlobalRequirements
- ThreadRequirements
The first four methods are designed to be statically imported from DefaultRequirements
.
See the API documentation for more details.
- Use
requireThat()
to verify pre-conditions of public APIs. - Use
assertThat()
to verify object invariants and method post-conditions. This results in excellent performance when assertions are disabled. Have your cake and eat it too! - Prefer
assertThat()
toassert
. It has a slightly higher overhead, but most applications fail to catch or logAssertionError
that is thrown byassert
, leading to silent failures.
Enhanced support is available for the following 3rd-party libraries and tools:
- Code licensed under the Apache License, Version 2.0
- Third party licenses
- Icons made by Flat Icons from www.flaticon.com is licensed by CC 3.0 BY