-1

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?

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • 1
    Different communities have different ideas about this. In Python, mutating functions typically return `None`. jQuery ecosystem returns `this` whenever possible; in Ruby one almost never returns `nil` except if the function explicitly does so. There is no objective answer to this question. – Amadan Nov 25 '21 at 04:47

1 Answers1

0

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.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • Thank you for answering this question. I found many concepts I have never heard. I have been in C# and Go, and got confused by the concept of functions/methods and mutability. I got a bit clearer after reading this answer and learning Haskell. –  Feb 02 '22 at 04:57