-
Notifications
You must be signed in to change notification settings - Fork 11
Calculator Example
Ben Fagin edited this page Aug 17, 2013
·
5 revisions
Let's build a calculator! Using the built-in BigInteger
class we can easily construct a fluent api to access some of the math operations.
public static class Result extends AtomicReference<BigInteger> { }
Descriptor descriptor = Flapi.builder()
.setDescriptorName("Calculator")
.setPackage("unquietcode.tools.flapi.examples.calculator.builder")
.setStartingMethodName("begin")
.startBlock("Calculation", "$(int startingValue)").last()
.addMethod("plus(int value)").any()
.addMethod("minus(int value)").any()
.addMethod("times(int value)").any()
.addMethod("divide(int value)").any()
.addMethod("power(int value)").any()
.addMethod("mod(int value)").any()
.addMethod("abs()").any()
.addMethod("equals()").last(Result.class)
.endBlock()
.build();
The usage is fairly straightforward, and looks something like this:
Result _result = CalculatorGenerator.begin(new CalculatorHelperImpl())
.$(0)
.plus(1)
.plus(1)
.power(5)
.divide(2)
.equals();
BigInteger result = _result.get();
System.out.println(result);
If you were to include this builder in a project, you might want to wrap some of the messiness involved with instantiating a new builder. A user of the calculator should not have to instantiate the helper or remember the $(...)
method to begin. Here I've introduced a Calculator
class which wraps all this up.
static class Calculator {
static CalculationBuilder<AtomicReference<BigInteger>> begin(int startingValue) {
CalculatorBuilder.$ result = CalculatorGenerator.begin(new CalculatorHelperImpl());
CalculationBuilder builder = result.$(startingValue);
return builder;
}
}
And now the usage is just a tiny bit cleaner:
Result = result = Calculator.begin(0)
.plus(1)
.plus(1)
.power(5)
.divide(2)
.equals();
System.out.println(result.get());
The full example can be found here.