Principle of fluent API design
Abstract
A “Cascading” API is designed to allow operations to be expressed via an unbroken sequence of chained method calls, but which can be split over multiple statements.
A “Fluent” API is a cascading API designed to always be expressed in a single statement.
Fluent APIs are good at encapsulating complex operations. Fluent APIs are a good pattern for domain specific operations.
A well-designed fluent API makes domain-specific operations more understandable & maintainable.
Benefits of Fluent APIs:
- encapsulating domain-specific operations,
- discoverability via auto-completion,
- hiding internal intermediate types,
- allowing lazy or short-cutting evaluation,
- reducing combinatorial explosion of method signatures,
- enforcing lexical rules via heterogeneous types.
Cons:
- Fluent APIs requires all parameters are available ⇒ normal use should not require explicit data collection.
- Fluent APIs will be misused at some point ⇒ consider runtime checks or static analysis.
- Fluent APIs not satisfying common use cases will be frustrating ⇒ provide an escape hatch if needed, or even a separate API.