From 248bda0b4f6df9c7eed9b3fd3352ddff80e69e2c Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Sat, 30 Jun 2018 16:21:07 +0100 Subject: [PATCH] Add `Result.of(Callable)` to reduce boiler plate when calling --- .../java/net/kemitix/mon/result/Result.java | 17 ++++++++++ src/test/java/net/kemitix/mon/ResultTest.java | 31 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/main/java/net/kemitix/mon/result/Result.java b/src/main/java/net/kemitix/mon/result/Result.java index 70a81e7..30043e2 100644 --- a/src/main/java/net/kemitix/mon/result/Result.java +++ b/src/main/java/net/kemitix/mon/result/Result.java @@ -24,6 +24,7 @@ package net.kemitix.mon.result; import net.kemitix.mon.Functor; import net.kemitix.mon.maybe.Maybe; +import java.util.concurrent.Callable; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; @@ -73,6 +74,22 @@ public interface Result extends Functor> { return new Success<>(value); } + /** + * Create a Result for a output of the Callable. + * + * @param callable the callable to produce the result + * @param the type of the value + * @return a Result + */ + @SuppressWarnings("illegalcatch") + static Result of(final Callable callable) { + try { + return Result.ok(callable.call()); + } catch (final Exception e) { + return Result.error(e); + } + } + /** * Creates a Result from the Maybe, where the Result will be an error if the Maybe is Nothing. * diff --git a/src/test/java/net/kemitix/mon/ResultTest.java b/src/test/java/net/kemitix/mon/ResultTest.java index 2a2f35e..e8b24cd 100644 --- a/src/test/java/net/kemitix/mon/ResultTest.java +++ b/src/test/java/net/kemitix/mon/ResultTest.java @@ -6,6 +6,9 @@ import net.kemitix.mon.result.Result; import org.assertj.core.api.WithAssertions; import org.junit.Test; +import java.io.IOException; +import java.util.concurrent.Callable; + public class ResultTest implements WithAssertions { @Test @@ -396,6 +399,34 @@ public class ResultTest implements WithAssertions { assertThat(toString).contains("Result.Error{error=java.lang.RuntimeException: failed}"); } + @Test + public void resultOf_okay_isOkay() { + //given + final Callable c = () -> "okay"; + //when + final Result result = Result.of(c); + //then + result.match( + success -> assertThat(success).isEqualTo("okay"), + error -> fail("not an error") + ); + } + + @Test + public void resultOf_error_isError() { + //given + final Callable c = () -> { + throw new IOException(); + }; + //when + final Result result = Result.of(c); + //then + result.match( + success -> fail("not a success"), + error -> assertThat(error).isInstanceOf(IOException.class) + ); + } + @RequiredArgsConstructor private static class UseCase {