Search code examples
oopfunctional-programmingcoding-stylefunction-composition

Should I return the object itself just for function chain


I have been wondering whether should I return the object itself from a setter or procedure (returning void originally), so that all the function can chain together.

We've all been taught to return void when there is nothing to return, but is returning the object itself better then returning void?


Solution

  • When the operation in question is a mutating operation, you don't have any 'natural' return value. This means that you have an opportunity to return whatever you'd like to - for example the object itself.

    In OOP, if you return the object itself, you'll effectively enable a Fluent Interface. While this enables method chaining it also exposes you to aliasing issues, so it's an open question whether or not this is a net benefit.

    In FP, state mutation breaks referential transparency, so well-designed FP APIs don't allow setters or mutating operations at all. Instead, you'd use copy-and-update where a function returns a copy of the original input, with a few things changed. This is so common in FP that languages like F# and Haskell has special syntax for such operations.

    You can see examples of all three styles (1. mutation, 2. Fluent Interface, 3. Copy-and-update) compared and contrasted in my article Builder isomorphisms.