Design Pattern - (Fluent Interface|Method Chaining)

1 - 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.

Spark script uses heavily this concept to process data.

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

3 - 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.

4 - Example

4.1 - 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);

4.2 - Fluent

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

5 - Documentation / Reference

code/design_pattern/fluent_interface.txt ยท Last modified: 2018/06/23 21:59 by gerardnico