Design Pattern - (Fluent Interface|Method Chaining)

> Code - (Programming|Computer) Language > Design Pattern

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();
OrderLine line1 = new OrderLine(6, Product.find("TAL"));
OrderLine line2 = new OrderLine(5, Product.find("HPK"));
OrderLine line3 = new OrderLine(3, Product.find("LGV"));

4.2 - Fluent

.with(6, "TAL")
.with(5, "HPK").skippable()
.with(3, "LGV")

5 - Documentation / Reference

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