Search code examples
oopdslmethod-chainingfluent-interface

Is it necessary to return the same object in methods with fluent interface


in some sources such as the original article of Martin Fowler aren't written that methods would return the same object, and methods in examples return different objects but in some sources(newer) such as Wikipedia is written that method would return the same object, which is correct?


Solution

  • There is no correct or right way to write fluent interface.

    Even Fowler's article uses both kinds of returned objects, but you don't see it easily because it shows usage, not the implementation.

    Usually when you are configuring some object, it will only make sense that you return the same object. Otherwise you would have to clone it first and then apply additional value.

    But there are scenarios where fluent interface will eventually return some other object in the sequence regardless if it is the same or of some other type.