A fluent interface provides an easy-readable, flowing interface, that often mimics a domain specific language. Using this pattern results in code that can be read nearly as human language.
The Fluent Interface pattern is useful when you want to provide an easy readable, flowing API. Those interfaces tend to mimic domain specific languages, so they can nearly be read as human languages.
A fluent interface can be implemented using any of
- Method chaining - calling a method returns some object on which further methods can be called.
- Static factory methods and imports.
- Named parameters - can be simulated using static factory methods.
Real world example
We need to select numbers based on different criteria from the list. It's a great chance to utilize fluent interface pattern to provide readable easy-to-use developer experience.
Fluent Interface pattern provides easily readable flowing interface to code.
In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL).
Use the Fluent Interface pattern when
- You provide an API that would benefit from a DSL-like usage.
- You have objects that are difficult to configure or use.