From 357335779e596dd697abc2cd45fa535660c5a354 Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Mon, 24 Apr 2017 13:35:02 +0100 Subject: [PATCH] Value: cache True/FalseValueClauses Rather than create a new transient object every time when they can be stateless singletons. --- .../java/net/kemitix/conditional/Value.java | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/kemitix/conditional/Value.java b/src/main/java/net/kemitix/conditional/Value.java index 453b43b..5944a2d 100644 --- a/src/main/java/net/kemitix/conditional/Value.java +++ b/src/main/java/net/kemitix/conditional/Value.java @@ -23,7 +23,12 @@ package net.kemitix.conditional; import lombok.RequiredArgsConstructor; +import java.util.AbstractMap.SimpleEntry; +import java.util.Collections; +import java.util.Map; import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; /** * A Value from an if-then-else in a functional-style. @@ -32,6 +37,14 @@ import java.util.function.Supplier; */ public interface Value { + ValueClause TRUE = new TrueValueClause(); + + ValueClause FALSE = new FalseValueClause(); + + Map VALUE_CLAUSES = Collections.unmodifiableMap( + Stream.of(new SimpleEntry<>(true, TRUE), new SimpleEntry<>(false, FALSE)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); + /** * Create a new {@link ValueClause} for the clause. * @@ -40,11 +53,9 @@ public interface Value { * * @return a true or false value clause */ + @SuppressWarnings("unchecked") static ValueClause where(final boolean clause) { - if (clause) { - return new TrueValueClause<>(); - } - return new FalseValueClause<>(); + return (ValueClause) VALUE_CLAUSES.get(clause); } /**