Skip to content

cowwoc/requirements.java

Repository files navigation

Maven Central build-status

checklist Fluent API for Design Contracts

API Changelog js

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.

Sample Code

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

Features

Getting Started

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:

The first four methods are designed to be statically imported from DefaultRequirements.

See the API documentation for more details.

Best practices

  • 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() to assert. It has a slightly higher overhead, but most applications fail to catch or log AssertionError that is thrown by assert, leading to silent failures.

3rd-party libraries and tools

Enhanced support is available for the following 3rd-party libraries and tools:

Licenses