Skip to content

Add support for Result-Pattern to Java-Client code #25

Description

@tomsontom

The TS/JS-Code is already using the result-pattern and with modern Java implementing a similar to TS/JS seems feasable

package at.bestsolution;

import java.util.List;
import java.util.function.Consumer;

public class Service {
    public sealed interface Result<T, E> permits Result.OK, Result.ERR {
        public final record OK<T, E>(T value) implements Result<T, E> {
            @Override
            public Result<T, E> onOK(Consumer<T> consumer) {
                consumer.accept(value);
                return this;
            }

            @Override
            public Result<T, E> onERR(Consumer<E> consumer) {
                return this;
            }
        }

        public final record ERR<T, E>(E error) implements Result<T, E> {
            @Override
            public Result<T, E> onOK(Consumer<T> consumer) {
                return this;
            }

            @Override
            public Result<T, E> onERR(Consumer<E> consumer) {
                consumer.accept(error);
                return this;
            }
        }

        public Result<T, E> onOK(Consumer<T> consumer);

        public Result<T, E> onERR(Consumer<E> consumer);

    }

    public sealed interface ErrorDoSomething permits AuthError, ValidationError {

    }

    public final record AuthError() implements ErrorDoSomething {

    }

    public final record ValidationError(List<String> validationErrors) implements ErrorDoSomething {

    }

    public <T> Result<String, ErrorDoSomething> doSomething() {
        return new Result.OK<>("Hello World");
    }

    public static void main(String[] args) {
        Service s = new Service();
        var r1 = s.doSomething();

        switch (r1) {
            case Result.OK(var value) -> handleOk(value);
            case Result.ERR(var error) -> {
                switch (error) {
                    case AuthError authError -> handleAuthError(authError);
                    case ValidationError(var validationErrors) -> handleValidationError(validationErrors);
                }
            }
        }
    }

    private static void handleOk(String value) {
        //
    }

    private static void handleAuthError(AuthError authError) {
        //
    }

    private static void handleValidationError(List<String> validationErrors) {
        //
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions