Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design an API with cascade function calls ( Class.doThis("...").doThat("...")..... )

I have seen that some API's are designed in the way that you must use them as below code

Class.doThis("...").doThat("...").....

For example HTTPCommon (Fluent API) can be used as:

Request.Get("http://somehost/")
        .connectTimeout(1000)
        .socketTimeout(1000)
        .execute().returnContent().asString();

The quartz-schedule can be used as:

JobDetail job = newJob(HelloJob.class)
               .withIdentity("job1", "group1")
               .build();

The SimpleCatptch can be used as:

Captcha captcha = new Captcha.Builder(200, 50)
                  .addText()
                  .addBackground()
                  .addNoise()
                  .gimp()
                  .addBorder()

What is the name of this kind of API design? When it is good to design like this?

like image 984
Alireza Fattahi Avatar asked May 05 '26 03:05

Alireza Fattahi


2 Answers

It's simply called "fluent", as HTTPCommon noted. It's common for builders to have a fluent layout, but the builder pattern is orthogonal: Fluent APIs are about readable chained method calls, while builders are about specifying a complete configuration for an object and then constructing it in a complete state all at once.

This style is appropriate whenever it makes the code readable; it's especially helpful when IDE autocompletion can assist the programmer. The two most common use cases are configurations (either builders or Spring-style configurers) and data pipelines (such as Java 8 streams and reactive programming).

like image 82
chrylis -cautiouslyoptimistic- Avatar answered May 08 '26 16:05

chrylis -cautiouslyoptimistic-


Your first example can be called method chaining.
Other examples have builder pattern, method chaining and fluent interface.

For a second part of your question see What is the difference between a fluent interface and the Builder pattern? and linked questions.

like image 23
Serikov Avatar answered May 08 '26 16:05

Serikov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!