From 29232d4e714ef49206f32dae44fd13d32d2e540b Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Fri, 21 Apr 2017 14:28:54 +0100 Subject: [PATCH] Condition: overload otherwise to allow if-then-else-if behaviour --- README.adoc | 19 +++++++++++++ .../net/kemitix/conditional/Condition.java | 11 ++++++++ .../kemitix/conditional/ConditionalTest.java | 27 +++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/README.adoc b/README.adoc index 45a63d9..e26b30f 100644 --- a/README.adoc +++ b/README.adoc @@ -131,6 +131,25 @@ Condition.where(isFalse()) .otherwise(() -> doSomethingElse()); ---- +### if-then-else-if + +[[source,java]] +---- +if (isFalse()) { + doSomething(); +} else if (isTrue()) { + doSomethingElse(); +} +---- + +[[source,java]] +---- +Condition.where(isFalse()) + .then(() -> doSomething()) + .otherwise(isTrue) + .then(() -> doSomethingElse()); +---- + ### if-then-if-then [[source,java]] diff --git a/src/main/java/net/kemitix/conditional/Condition.java b/src/main/java/net/kemitix/conditional/Condition.java index 6213b62..4df41e0 100644 --- a/src/main/java/net/kemitix/conditional/Condition.java +++ b/src/main/java/net/kemitix/conditional/Condition.java @@ -109,6 +109,17 @@ public interface Condition { */ void otherwise(Runnable response); + /** + * Create a new {@code Condition} for the clause as a continuation to an existing {@code Condition}. + * + * @param clause the condition to test + * + * @return the Condition + */ + default Condition otherwise(boolean clause) { + return where(clause); + } + /** * A {@code Condition} that has evaluated to {@code true}. */ diff --git a/src/test/java/net/kemitix/conditional/ConditionalTest.java b/src/test/java/net/kemitix/conditional/ConditionalTest.java index 87209cc..67c52a1 100644 --- a/src/test/java/net/kemitix/conditional/ConditionalTest.java +++ b/src/test/java/net/kemitix/conditional/ConditionalTest.java @@ -144,6 +144,28 @@ public class ConditionalTest { thenTheThenResponseRuns(); } + @Test + public void whereFalseElseTrueThenOtherwiseRuns() { + //when + Condition.where(false) + .then(thenResponse) + .otherwise(true) + .then(otherwiseResponse); + //then + thenTheOtherwiseResponseRuns(); + } + + @Test + public void whereFalseElseFalseThenNothingRuns() { + //when + Condition.where(false) + .then(thenResponse) + .otherwise(false) + .then(otherwiseResponse); + //then + thenNoResponseRuns(); + } + private void whenOr(final boolean firstClause, final boolean secondClause) { Condition.where(firstClause) .or(secondClause) @@ -172,6 +194,11 @@ public class ConditionalTest { assertThat(otherwiseFlag).isTrue(); } + private void thenNoResponseRuns() { + assertThat(thenFlag).isFalse(); + assertThat(otherwiseFlag).isFalse(); + } + private void when(final boolean firstClause, final boolean secondClause) { Condition.where(firstClause) .and(secondClause)