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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With