Fluent interfaces
Fluent interfaces provide a convenient and easy-to-use technique for expressing solutions to many different types of problems. They are similar to method chaining but are more natural to use. It is a form of function composition where the method invocations are chained together. In this section, we will discuss the difference and similarities between method chaining, method cascading, and fluent interfaces.
Java supported fluent styles before Java 8 though their use was not common. For example, in JavaFX 2 the IntegerProperty
class possesses a number of numerical methods that return the NumberBinding
instances. These methods are used in a fluent style as shown here:
IntegerProperty n1 = new SimpleIntegerProperty(5); IntegerProperty n2 = new SimpleIntegerProperty(2); IntegerProperty n3 = new SimpleIntegerProperty(3); NumberBinding sum = n1 .add(n2) .multiply(n3); System.out.println(sum.getValue());
A value of 21
is displayed. The use...