Search code examples
apidslfluent-interfacemethod-chaining

How are fluent API's different from other API's?


I have come across fluent API's while studying DSLs.
I have searched a lot on fluent API's...the basic conclusion which I could draw was that fluent a API uses method chaining in order to make the code fluent.
But I cannot understand - in object oriented languages we can always create an object and can call the methods related to it. Then how is a fluent API different? What other features does a fluent API add?


Solution

  • With a fluent interface you write methods that return the object that the method was invoked on (usually self or this) and handle traditional return values as a state change in that object. If you look at say some of the Javascript libraries that use a fluent interface it makes it far easier to deal with lists and nulls as they can be handled the same way you would a single object. The disadvantage of fluent interfaces is that they tend to create monolithic god objects that have a whole heap of responsibilities.

    I wouldn't want them to be used everywhere (because of the god object problem) but they are nice from time to time.