BAEL-2303 Updated the code as per the review comments.
This commit is contained in:
@@ -1,19 +1,17 @@
|
||||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class AddCommand implements Command<Integer, Integer, Integer> {
|
||||
public class AddCommand implements Command {
|
||||
|
||||
private int a;
|
||||
private int b;
|
||||
|
||||
public AddCommand(int a, int b) {
|
||||
this.a = a;
|
||||
this.b = b;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer execute() {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Command<Integer, Integer, Integer> takeInput(Integer a, Integer b) {
|
||||
this.a = a;
|
||||
this.b = b;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ public class AddRule implements Rule {
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getResult() {
|
||||
return result;
|
||||
public Result getResult() {
|
||||
return new Result(result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,8 +77,7 @@ public class Calculator {
|
||||
return targetOperation.apply(a, b);
|
||||
}
|
||||
|
||||
public int calculate(int a, int b, Command<Integer, Integer, Integer> command) {
|
||||
return command.takeInput(a, b)
|
||||
.execute();
|
||||
public int calculate(Command command) {
|
||||
return command.execute();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public interface Command<A, B, R> {
|
||||
R execute();
|
||||
|
||||
Command<A, B, R> takeInput(A a, B b);
|
||||
}
|
||||
public interface Command {
|
||||
Integer execute();
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Result {
|
||||
int value;
|
||||
|
||||
public Result(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -4,5 +4,5 @@ public interface Rule {
|
||||
|
||||
boolean evaluate(Expression expression);
|
||||
|
||||
int getResult();
|
||||
Result getResult();
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.baeldung.reducingIfElse;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class RuleEngine {
|
||||
@@ -12,9 +13,12 @@ public class RuleEngine {
|
||||
rules.add(new AddRule());
|
||||
}
|
||||
|
||||
public List<Rule> process(Expression expression) {
|
||||
return rules.stream()
|
||||
public Result process(Expression expression) {
|
||||
|
||||
Rule rule = rules.stream()
|
||||
.filter(r -> r.evaluate(expression))
|
||||
.collect(Collectors.toList());
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Expression does not matches any Rule"));
|
||||
return rule.getResult();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user