liveBook · Manning

Fluent interface

As explained in Effective Behavior-Driven Development

An API design style in which chained calls or expressions read as a sequence of operations.

A fluent interface lets method calls be chained into a sequence that reads like an instruction. In an Object Mother, customization methods return the Object Mother itself, so an order can be configured and then built in one expression. section 14.3

When choosing this style, weigh readability against implementation and debugging costs:

  • Chaining can make configuration less verbose and help readers check whether the instructions fit the task. section 14.3
  • A traditional interface remains an option; fluent methods require extra implementation code and can sometimes be harder to debug. section 14.3
Listing 14.11 Step definitions that use the object mother for building the order
*** StepDefinitions/OrderingStepDefinitions.cs ***
[Given("the customer has placed an order containing a {string} pizza")]
public void GivenTheCustomerHasPlacedAnOrderContaining(string pizzaName)
{
  var order = new OrderObjectMother()    #A
    .WithItem(name: pizzaName)
    .Build();
  ...
}

[When("the customer places an order for {int} pizza(s) of size {string}")]
public void WhenTheCustomerPlacesAnOrderFor(int count, string pizzaSize)
{
  var order = new OrderObjectMother()    #B
    .WithItems(count, size: pizzaSize)
    .Build();
  ...
}

[Given("the customer has placed an order")]
public void GivenTheCustomerHasPlacedAnOrder()
{
  var order = new OrderObjectMother().Build();    #C
  ...
}

The order-building calls chain customization methods before Build returns the configured order. section 14.3

How Effective Behavior-Driven Development covers it

How deep it goes
Defines chaining through methods returning their class and weighs readability against implementation effort and debugging difficulty.
Examples
Shows an order configured with WithItem or WithItems and completed with Build, contrasted with separate calls.
What you can do after
Apply fluent chaining to configure an order through an Object Mother before building it.
How it connects
Connects fluent interfaces with the Object Mother pattern and test data setup.

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 Effective Behavior-Driven Development. The section links point to the parts of the book it draws on.