All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.mike10004.containment.lifecycle.Computation Maven / Gradle / Ivy

There is a newer version: 0.6
Show newest version
package io.github.mike10004.containment.lifecycle;

import java.util.Optional;
import java.util.StringJoiner;

class Computation implements Provision {

    private final D provisioned;
    private final Throwable exception;
    @SuppressWarnings("OptionalUsedAsFieldOrParameterType")
    private transient final Optional optional;

    protected Computation(D provisioned, Throwable exception) {
        if (provisioned != null && exception != null) {
            throw new IllegalArgumentException("either it was provisioned or an exception was thrown; make up your mind");
        }
        if (provisioned == null && exception == null) {
            throw new IllegalArgumentException("if computation succeeded, provisioned value must be non-null");
        }
        this.provisioned = provisioned;
        this.exception = exception;
        optional = Optional.ofNullable(provisioned);
    }

    @Override
    public Optional asOptional() {
        return optional;
    }

    public static  Computation succeeded(D value) {
        return new Computation<>(value, null);
    }

    public static  Computation failed(Throwable t) {
        return new Computation<>(null, t);
    }

    @Override
    public D value() {
        return provisioned;
    }

    @Override
    public Throwable exception() {
        return exception;
    }

    @Override
    public String toString() {
        StringJoiner j = new StringJoiner(", ", Computation.class.getSimpleName() + "[", "]");
        if (provisioned != null) {
            j.add("provisioned=" + provisioned);
        }
        if (exception != null) {
            j.add("exception=" + exception);
        }
        return j.toString();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy