-
Notifications
You must be signed in to change notification settings - Fork 10
Calculator Example
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.
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(ObjectWrapper.class)
.endBlock()
.build();The return type is set to ObjectWrapper because we need an immutable reference to hold on to, but the BigInteger class is itself immutable (math operations return a new object).
The usage is fairly straightforward, and looks something like this:
ObjectWrapper _result = CalculatorGenerator.begin(new CalculatorHelperImpl())
.$(0)
.plus(1)
.plus(1)
.power(5)
.divide(2)
.equals();
BigInteger result = (BigInteger) _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<ObjectWrapper<BigInteger>> begin(int startingValue) {
CalculatorBuilder result = CalculatorGenerator.begin(new CalculatorHelperImpl());
@SuppressWarnings("unchecked")
CalculationBuilder<ObjectWrapper<BigInteger>> started
= (CalculationBuilder<ObjectWrapper<BigInteger>>) result.$(startingValue);
return started;
}
}And now the usage is just a tiny bit cleaner:
ObjectWrapper<BigInteger> 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.