June 24, 2026

Railway Oriented Programming

In Progress / Under Development

This system architectural record is currently being refined.

In Railway Oriented Programming, we model operations as two-track pathways using an Either<T, E> structure. Here is how we can implement this elegant pattern in Java 21:

public sealed interface Either<T, E> permits Either.Right, Either.Left {
    
    record Right<T, E>(T value) implements Either<T, E> {}
    record Left<T, E>(E error) implements Either<T, E> {}

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

    static <T, E> Either<T, E> left(E error) {
        return new Left<>(error);
    }

    default boolean isRight() {
        return this instanceof Right;
    }

    default boolean isLeft() {
        return this instanceof Left;
    }

    @SuppressWarnings("unchecked")
    default <U> Either<U, E> map(java.util.function.Function<T, U> mapper) {
        return switch (this) {
            case Right<T, E> r -> Either.right(mapper.apply(r.value()));
            case Left<T, E> l -> (Either<U, E>) l;
        };
    }

    @SuppressWarnings("unchecked")
    default <U> Either<U, E> flatMap(java.util.function.Function<T, Either<U, E>> mapper) {
        return switch (this) {
            case Right<T, E> r -> mapper.apply(r.value());
            case Left<T, E> l -> (Either<U, E>) l;
        };
    }
}

Below is the design diagram illustrating the Success Track vs Failure Track:

Railway Oriented Programming Diagram

Lat: 25.2637° S
Lon: 57.5759° W
Node_Primary: Active Uptime: 99.999%