Skip to content
AF2BPublic

Repository files navigation

Result

Maven Central Javadoc OpenSSF Scorecard

Result<T, E> for Java 21: success or error as a value, matched exhaustively. The core has no runtime dependencies.

Installation

Maven:

<dependency>
  <groupId>io.github.af2b</groupId>
  <artifactId>result</artifactId>
  <version>3</version>
</dependency>

Gradle:

implementation("io.github.af2b:result:3")

Every artifact has the same version and the group io.github.af2b:

Artifact What it adds Java module Since
result Result and its helpers, without dependencies io.github.af2b.result 1
result-jackson JSON with Jackson 2 io.github.af2b.result.jackson 3
result-jackson3 JSON with Jackson 3 io.github.af2b.result.jackson3 3
result-assertj AssertJ assertions, for the test scope io.github.af2b.result.assertj 3
result-jqwik jqwik arbitraries, for property tests io.github.af2b.result.jqwik 4
result-spring Spring MVC responses, errors as RFC 9457 problem details io.github.af2b.result.spring 4
result-validation Jakarta Validation violations as a result io.github.af2b.result.validation 4
result-vavr conversions to and from the Either, Try and Validation of Vavr io.github.af2b.result.vavr 4

With Java modules, add requires io.github.af2b.result; to module-info.java, or the module of the artifact you use. Each extra module requires the core and its library transitively.

Usage

sealed interface AgeError {}
record NotANumber(String text) implements AgeError {}
record Negative(int value) implements AgeError {}

static Result<Integer, AgeError> parseAge(String text) {
  return Result.attempt(NumberFormatException.class, () -> Integer.parseInt(text))
      .mapErrorTo(AgeError.class, thrown -> new NotANumber(text))
      .filter(age -> age >= 0, Negative::new);
}

static String describe(Result<Integer, AgeError> result) {
  return switch (result) {
    case Result.Ok<Integer, AgeError>(var age) -> "age " + age;
    case Result.Err<Integer, AgeError>(var error) ->
        switch (error) {
          case NotANumber(var text) -> "not a number: " + text;
          case Negative(var value) -> "negative: " + value;
        };
  };
}

No switch has a default. A new case in AgeError breaks the build until it is handled.

To validate many items and keep every error:

static Result<List<Integer>, NonEmptyList<AgeError>> parseAges(List<String> lines) {
  return Result.traverseAll(lines, line -> parseAge(line));
}

To combine independent fields and keep every error, in argument order:

record Ages(int first, int second, int third) {}

static Result<Ages, NonEmptyList<AgeError>> parseThree(String a, String b, String c) {
  return Result.zipAll(parseAge(a), parseAge(b), parseAge(c), Ages::new);
}

Recipes

Keep the valid lines and drop the others:

static List<Integer> validAges(List<String> lines) {
  return lines.stream().map(line -> parseAge(line)).flatMap(Result::stream).toList();
}

Merge the errors kept by zipAll into one:

static Result<Ages, String> parseThreeAsText(String a, String b, String c) {
  return parseThree(a, b, c)
      .mapError(errors -> errors.map(Object::toString).reduce((left, right) -> left + "; " + right));
}

Validate a form and report every invalid field:

sealed interface FormError {}
record InvalidEmail(String value) implements FormError {}
record InvalidAge(String value) implements FormError {}
record SignUp(String email, int age) {}

static Result<SignUp, NonEmptyList<FormError>> signUp(String email, String age) {
  Result<String, FormError> checkedEmail =
      Result.<String, FormError>ok(email).filter(text -> text.contains("@"), InvalidEmail::new);
  Result<Integer, FormError> checkedAge =
      parseAge(age).mapErrorTo(FormError.class, error -> new InvalidAge(age));
  return Result.zipAll(checkedEmail, checkedAge, SignUp::new);
}

Turn asynchronous code into a result, with the rules of attempt:

static CompletionStage<Result<String, IOException>> download(CompletionStage<String> request) {
  return Result.fromStage(IOException.class, request);
}

Run every step concurrently and wait for all, keeping the order of the items:

static CompletionStage<Result<List<Integer>, AgeError>> parseAllAsync(
    List<String> lines, Executor executor) {
  return Result.traverseAsync(
      lines, line -> CompletableFuture.supplyAsync(() -> parseAge(line), executor));
}

Start from a value that may be null, and act on the outcome at the end of the chain:

static void printAge(Map<String, String> settings) {
  Result.ofNullable(settings.get("age"), () -> "no age")
      .flatMap(text -> parseAge(text).mapError(Object::toString))
      .ifOkOrElse(age -> System.out.println("age " + age), System.err::println);
}

Work next to code that throws, and throw again at the edge:

static String readName(Path file) throws IOException {
  return Result.attempt(IOException.class, () -> Files.readString(file))
      .map(String::strip)
      .filter(name -> !name.isEmpty(), name -> new IOException("empty file: " + file))
      .orElseThrow(error -> error);
}

JSON

Add result-jackson for Jackson 2 and register its ResultModule. A success is written as {"ok": value} and a failure as {"err": error}:

static final ObjectMapper MAPPER = new ObjectMapper().registerModule(new ResultModule());

static Result<Integer, String> fromJson(String json) throws JsonProcessingException {
  return MAPPER.readValue(json, new TypeReference<Result<Integer, String>>() {});
}

Reading needs the full type, as in the TypeReference above. JSON of any other shape, holding null, or a JSON null or missing field where a result is expected, is rejected.

For Jackson 3, add result-jackson3 instead. Its ResultModule writes and reads the same JSON:

static final JsonMapper JSON_MAPPER =
    JsonMapper.builder().addModule(new io.github.af2b.result.jackson3.ResultModule()).build();

static String toJson(Result<Integer, String> result) {
  return JSON_MAPPER.writeValueAsString(result);
}

Both modules run in a GraalVM native image without reflection configuration; make native checks it.

Spring MVC

Add result-spring and declare a ResultResponseAdvice bean. Controllers then return a Result: a success answers 200 OK with the value as the body, Unit answers 204 No Content, and an error answers with the RFC 9457 problem detail its mapper builds, as application/problem+json:

@Bean
static ResultResponseAdvice resultResponseAdvice() {
  return new ResultResponseAdvice(
      error ->
          switch (error) {
            case NotANumber(var text) ->
                ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Not a number: " + text);
            case Negative(var value) ->
                ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Negative: " + value);
            default -> ProblemDetail.forStatus(HttpStatus.INTERNAL_SERVER_ERROR);
          });
}

@RestController
static final class AgeController {
  @GetMapping("/ages/{text}")
  Result<Integer, AgeError> age(@PathVariable("text") String text) {
    return parseAge(text);
  }
}

Without a mapper, errors that are Spring ErrorResponses keep their own problem detail and any other error answers a bare 500, so nothing internal reaches the client. Where a ResponseEntity is needed, such as for 201 Created, ResultResponses.toResponse builds the same responses.

Jakarta Validation

Add result-validation to get the violations of a bean as a result, sorted by property path so the same bean always gives the same list:

record Account(@NotBlank String name, @Min(0) int age) {}

static Result<Account, NonEmptyList<String>> checkAccount(Validator validator, Account account) {
  return BeanValidation.validate(validator, account)
      .mapError(
          violations ->
              violations.map(violation -> violation.getPropertyPath() + " " + violation.getMessage()));
}

Vavr

Add result-vavr to call code written with Vavr, or to move away from it one module at a time:

static Either<AgeError, Integer> parseAgeForVavr(String text) {
  return VavrResults.toEither(parseAge(text));
}

static Result<Integer, Throwable> fromVavr(Try<Integer> attempt) {
  return VavrResults.fromTry(attempt);
}

Tests

Add result-assertj in the test scope and import ResultAssert.assertThat statically, next to the assertThat of AssertJ:

static void checkParseAge() {
  assertThat(parseAge("42")).isOk().hasValue(42);
  assertThat(parseAge("-1")).hasError(new Negative(-1));
  assertThat(parseAge("x")).hasErrorSatisfying(error -> assertThat(error).isInstanceOf(NotANumber.class));
}

A failed check prints the whole result, so it shows the error that was not expected.

Add result-jqwik in the test scope, and jqwik generates @ForAll parameters of type Result and NonEmptyList from the arbitraries of their type arguments. ResultArbitraries builds them explicitly, for @Provide methods:

@Property
void swappingTwiceChangesNothing(@ForAll Result<Integer, String> result) {
  assertThat(result.swap().swap()).isEqualTo(result);
}

Every Java example of this file is compiled by make check.

Operations

Group Methods
create ok, err, fromOptional, ofNullable, attempt, attemptRun, fromStage
JSON ResultModule for Jackson 2 or Jackson 3
transform map, mapError, mapErrorTo, mapBoth, flatMap, flatten, filter, swap
combine, first error zip, sequence, traverse (lists and streams), toResultList
combine, every error zipAll (2 to 8 results), sequenceAll, traverseAll, partition, toPartition
combine, asynchronous sequenceAsync, sequenceAllAsync, traverseAsync
observe peek, peekError
consume fold, getOrElse, orElseThrow, toOptional, errorOptional, stream, isOk, isErr, ifOk, ifErr, ifOkOrElse
recover recover, orElse
NonEmptyList of, from, toNonEmptyList, map, flatMap, filter, append, concat, reduce, last, stream
  • Values and errors are never null. Use Unit for a success without a value.
  • toOptional and stream discard the error; errorOptional discards the value.
  • Results, NonEmptyList and Partition are serializable when what they hold is.
  • The asynchronous methods wait for every stage, in the order given; an error does not cancel the other stages.
  • NonEmptyList.reduce merges the errors kept by zipAll and traverseAll into one, with no seed.
  • The Javadoc of each type and method says with @since the version that added it. Its examples are regions of the tests, so they compile and pass with every build.
  • attempt captures only the expected exception. Anything else propagates.
  • toResultList consumes the whole stream before giving the first error. sequence and traverse on a stream stop at it.
  • fromStage applies the rules of attempt to a CompletionStage.
  • The package is annotated with @CheckReturnValue: Error Prone reports a result that is ignored.
  • On JDK 22 and newer, NullAway also checks nullness inside generic types when they are assigned or returned, such as List<@Nullable String> where List<String> is expected. It does not yet catch every case reached through type inference.

Performance

ComparisonBenchmark writes one rule four ways and rejects an input that breaks it, as most expected failures do. On an Intel Core i5-12400F with JDK 25, make bench BENCH_ARGS="ComparisonBenchmark -wi 3 -i 5" gave:

Way Accepted, ns Rejected, ns Rejected, bytes allocated
Result 2.3 3.8 32
Vavr Either 2.0 3.8 32
exception 0.4 492 728
Optional 2.0 0.8 0, and the reason is lost

A result costs what an Either costs. Rejecting with an exception costs about 130 times more, most of it to fill the stack trace. The numbers vary with the machine; run the benchmark on yours before relying on them.

Development

Requirements: JDK 21 or newer and make. The Maven Wrapper downloads the pinned Maven.

Command What it does
make build compiles; any warning fails
make test runs the tests, property tests included
make mutation runs mutation testing; a surviving mutant fails
make bench runs the JMH benchmarks with the allocation profiler; BENCH_ARGS=ComparisonBenchmark runs only the comparison below
make fuzz-build builds the Jazzer fuzz targets of fuzz/ and runs them on their seeds; ClusterFuzzLite fuzzes them in CI
make format formats the code with google-java-format
make lint fails on unformatted code
make docs builds the Javadoc; any warning fails
make check compiles with Error Prone and NullAway, tests, builds the jars Maven Central receives, compiles the README examples and uses the jars as a consumer
make reproducible builds every jar twice and fails unless both builds are identical
make native runs both JSON modules in a GraalVM native image; needs native-image
make install installs every module in the local Maven repository
make release TAG=v1 uploads to Maven Central
make github-release TAG=v1 publishes the GitHub release with the notes of CHANGELOG.md
make clean removes build output

Publishing

Every release attaches the signed jars, poms and CycloneDX SBOMs of every module to its GitHub release, and the jars carry a build provenance attestation, which gh attestation verify result-N.jar --repo AF2B/Result checks. The build is reproducible: the same sources give the same jars, byte for byte. Releases go to Maven Central under the io.github.af2b namespace. The release workflow signs them with a GPG key and reads the repository secrets CENTRAL_USERNAME, CENTRAL_PASSWORD (a portal token), GPG_PRIVATE_KEY and GPG_PASSPHRASE.

Versions are whole numbers: v1, v2, v3. The Maven version is the same number without the v, such as 1. Any new version may change the API, so CHANGELOG.md says what changed.

Then, for each release:

  1. Set a version without -SNAPSHOT in every pom.xml, move the [Unreleased] notes of CHANGELOG.md under ## [N] - date, and merge into main. The GitHub release takes its notes from that section.
  2. Push the tag vN. The release workflow uploads the artifact and publishes the GitHub release.
  3. Confirm the publication in the portal. A published version cannot be changed or removed.
  4. Merge the pull request the workflow opens to move to the next -SNAPSHOT version and compare the API with the release. Close and reopen it first, so CI runs.

make check fails when a change breaks code written against the last release. To break the API on purpose, set api.breakOnChange to false in pom.xml and explain the break in CHANGELOG.md; the next-version pull request turns the check back on.

Contributing

See CONTRIBUTING.md. Report vulnerabilities as described in SECURITY.md.

License

MIT. See LICENSE.

Releases

Packages

Contributors

Languages