Either Type in Functional Programming

The Either type is a versatile design pattern used in functional programming to represent a value that can be one of two possible types. It is particularly useful for handling operations that can result in either a success or an error, providing a more expressive alternative to traditional error handling mechanisms like exceptions.

Overview

The Either type can hold a value of type T or a value of type U. It is similar to the Option type but is distinguished by its two subclasses: Left and Right. By convention, Right is used to represent a successful outcome, while Left is used to represent an error or an alternative outcome. This convention aligns with the idea that "right" is synonymous with "correct" or "successful."

Implementation

The Either type can be implemented by modifying the Option type to accommodate two possible values instead of one. The following listing demonstrates how to design an Either type with two private subclasses, Left and Right, to encapsulate the two potential values.

[Listing 7.1. The Either type](https://livebook.manning.com/book/functional-programming-in-java/chapter-7/24)

public abstract class Either<T, U> {

  private static class Left<T, U> extends Either<T, U> {

    private final T value;

    private Left(T value) {
      this.value = value;
    }

    @Override
    public String toString() {
      return String.format("Left(%s)", value);
    }
  }

  private static class Right<T, U> extends Either<T, U> {

    private final U value;

    private Right(U value) {
      this.value = value;
    }
    @Override
    public String toString() {
      return String.format("Right(%s)", value);
    }
  }

  public static <T, U> Either<T, U> left(T value) {
    return new Left<>(value);
  }

  public static <T, U> Either<T, U> right(U value) {
    return new Right<>(value);
  }
}

In this implementation, the Either type is an abstract class with two private static subclasses, Left and Right. Each subclass holds a value of a specific type, T for Left and U for Right. The static methods left and right are provided to create instances of these subclasses.

Usage

The Either type is particularly useful in scenarios where a function can return either a result or an error. By parameterizing Either with the type of the data and the type of the error, developers can clearly express the dual nature of the function's output. This approach enhances code readability and maintainability by making the potential outcomes explicit.

For example, when performing an operation that might fail, such as reading from a file or parsing a number, the Either type can be used to return a Right instance with the result on success or a Left instance with an error message or code on failure. This pattern encourages handling both success and error cases explicitly, reducing the likelihood of unhandled exceptions and improving the robustness of the code.