About

Same technique that the builder pattern to build an Domain Specific Language in declarative way.

The API is primarily designed to be readable and to flow between methods/functions

Spark script uses heavily this concept to process data.

Method chaining lets you write shorter code (and waste less time fretting over variable names).

Implementation

All methods return the same object (a reference to the data).

Typically, a method returns a reference to the element that it just acted on, but not always. When chaining methods, order matters. The output type of one method has to match the input type expected by the next method in the chain.

Example

Non Fluent

Order o1 = new Order();
customer.addOrder(o1);
OrderLine line1 = new OrderLine(6, Product.find("TAL"));
o1.addLine(line1);
OrderLine line2 = new OrderLine(5, Product.find("HPK"));
o1.addLine(line2);
OrderLine line3 = new OrderLine(3, Product.find("LGV"));
o1.addLine(line3);
line2.setSkippable(true);
o1.setRush(true);

Fluent

customer.newOrder()
.with(6, "TAL")
.with(5, "HPK").skippable()
.with(3, "LGV")
.priorityRush();

Documentation / Reference