Fluent APIs, a.k.a, fluent interfaces, are object-oriented APIs designed with the intent that the API code is more readable and therefore easier to use. Wiring objects together via method chaining is the main feature that helps to accomplish these readability and usability goals. Chained methods, in this design, generally maintain the same type.
// StringBuilder API
StringBuilder
sb
=
new
StringBuilder
(
"palindrome!"
);
// Method chaining
sb
.
delete
(
10
,
11
).
append
(
"s"
).
reverse
();
System
.
out
.
println
(
"Value: "
+
sb
);
$
Value:
semordnilap
To name a few popular fluent APIs written in Java, there is the Java Object Oriented Querying (jOOQ) API, the jMock testing API, the Calculon Android testing API, the Apache Camel integration patterns API, Java 8’s Date Time API (JSR 310) and Java 9’s Money and Currency API (JSR 354). Each of these are considered to contain a Java Domain Specific Language (DSL).
An external DSL can be easily mapped into a new Java internal DSL by using the fluent API approach.
Common method prefixes used in fluent APIs, and acting on objects, include at
, format
, from
, get
, to
, and with
,.
The LocalDateTime
class of the Date Time API is represented here without and with method chaining.
// Standalone static method
LocalDateTime
ldt1
=
LocalDateTime
.
now
();
System
.
out
.
println
(
ldt1
);
$
2014
-
02
-
26
T09:
33
:
25.676
// Static method with method chaining
LocalDateTime
ldt2
=
LocalDateTime
.
now
()
.
withDayOfMonth
(
1
).
withYear
(
1878
)
.
plusWeeks
(
2
).
minus
(
3
,
ChronoUnit
.
HOURS
);
System
.
out
.
println
(
ldt2
);
$
1878
-
02
-
15
T06:
33
:
25.724