4

When I want to write a class in Coffeescript that provides method chaining I often come up with the problem of having a one liner in principle but then having to add a line to actually return the instance for the chaining.

So instead of writing a simple setter like this:

class myClass
    setProperty: (value) -> @property = value

I have to break it up and do it like this:

class myClass
    setProperty: (value) ->
        @property = value
        @

In my eyes this really reduces readability and compactness of the code, especially if you have plenty of setters and other self-explanatory one liners.

So I thought about doing it another way and reintroducing the semicolon to my code, like this:

class myClass
    setProperty: (value) -> @property = value; @

The compiled JavaScript is actually the same, but while it's pretty handy it also feels a little dirty to do it that way.

How would you serve the purpose of method chaining (if you'd use it) in Coffeescript?

EDIT: The best solution I got so far, a clean and short one-liner without any semicolons:

class myClass
    setProperty: (@property) -> @
Loilo
  • 13,466
  • 8
  • 37
  • 47
  • 1
    This is the ultimate opinion-based question. Either method is, as you say, identical. Pick the one you like most. – user229044 Jan 02 '15 at 23:49
  • 1
    You also could write a wrapper funtion: `chain=(fn)-> ()-> (fn.apply @,arguments); @`, and use it like this: `… setProperty: chain (value)-> @property = value …` Or you can use the ECMA 5 internal setters with `Object.defineProperty`. as @meagar has mentioned, it is purely a question of taste. – Patrick J. S. Jan 03 '15 at 08:21
  • That's pretty much all I need. I only wanted to know if it is commonly known as a bad habit or stuff, thanks. – Loilo Jan 03 '15 at 11:37
  • @PatrickJ.S. That's a horrible solution. You've replaced one extra character with 5, introduced an extra function call to every method invocation, and broken the `super` keyword – user229044 Jan 03 '15 at 16:01

0 Answers0