Skip to Content
Java Pocket Guide, 4th Edition
book

Java Pocket Guide, 4th Edition

by Robert Liguori, Patricia Liguori
August 2017
Intermediate to advanced
290 pages
4h 10m
English
O'Reilly Media, Inc.
Content preview from Java Pocket Guide, 4th Edition

Appendix A. Fluent APIs

Fluent APIs, a.k.a. fluent interfaces, are object-oriented APIs designed to make the API code more readable and therefore easier to use. Wiring objects together via method chaining helps accomplish these readability and usability goals. In this design and the following example, chained methods generally maintain the same type.

/*
 * Transform 'palindrome!' string
 * to 'semordnilap' string.
*/

// StringBuilder API
StringBuilder sb = new StringBuilder("palindrome!");

// Method chaining (delete, append, reverse)
sb.delete(10, 11).append("s").reverse();

System.out.println("New value: " + sb);
$ New 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 the Java Money and Currency API (JSR 354). Each of these is 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 include at, format, from, get, to, and with.

The LocalDateTime class of the Date Time API is represented here, with and without method chaining:

// 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-15T06:33:
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java 8 Pocket Guide

Java 8 Pocket Guide

Robert Liguori, Patricia Liguori
Java 11 Cookbook - Second Edition

Java 11 Cookbook - Second Edition

Nick Samoylov, Mohamed Sanaulla

Publisher Resources

ISBN: 9781491938683Errata Page