liveBook · Manning

Fluent interface

As explained in Data-Oriented Programming in Java

Fluent chaining is an API style in which successive operations are linked through return values to form an expression-like sequence.

A fluent interface links successive operations through return values, turning a sequence of transformations into a readable expression. With immutable values, each operation returns a new value rather than modifying the receiver. section 2.5

A fluent interface is especially useful when:

  • Operations naturally transform one value into another, as with repeated Ball.step calls. section 2.5
  • A domain model benefits from readable, composable expressions, such as vector transformations or business rules joined with and and or. section 2.5 section 8.4
  • The alternative would obscure the sequence through nested stand-alone calls or verbose function composition. section 2.5

Chaining immutable transformations

A Ball can compute successive states without mutation: ball.step(dt).step(dt).step(dt). Each call returns another Ball, so the final result is distinct from the original while the update sequence remains visible. section 2.5

Composing business rules

A rule algebra can expose default methods such as and and or, allowing expressions like eq(REGION, "EMEA").and(eq(SEGMENT, "Public")).or(not(eq(REGION, "LATAM"))). section 8.4

Listing 2.29 Fluent APIs for free
float dt = 1.0f;
Ball ball = new Ball(new Point(0.0, 0.0), new Vector(1.0, 0.0));  
Ball updated = ball   
    .step(dt)              #A
    .step(dt)              #A
    .step(dt);             #A
 
assertNotSame(updated, ball);    #B
assertNotEquals(updated, ball);  #B

Shows an immutable Ball transformation whose returned values support readable repeated chaining. section 2.5

How Data-Oriented Programming in Java covers it

How deep it goes
Explains chaining through returned values, contrasts nested alternatives, and stops short of broader API design guidance.
Examples
Demonstrates Ball.step, vector transformations, and rule expressions built with and, or, and not.
What it assumes
Assumes familiarity with Java methods, objects, interfaces, and immutable values.
What you can do after
Apply it via immutable value methods and default interface methods to build readable transformation or rule expressions.
How it connects
Connects fluent chaining to immutable data, value objects, vector transformations, and business rules as data.

Also explained in

Compare how 6 books explain fluent interface →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data-Oriented Programming in Java. The section links point to the parts of the book it draws on.