Site icon Adam N England

Fluent Interfaces in Coffeescript

We’ve all seen them – builder patterns that make object construction clean and readable.

person().named(‘Bob’).withSpouse(‘Alice’).bornOn(’01-26-1982′).build()

I used to do these all the time in Java (we called them fluent interfaces), and I just realized today that I had no idea how to do this style in Coffeescript. Well, lets remedy that.

To get started, I’m going to follow the basic pattern I’ve followed in Java. Since CoffeeScript provides native class functionality, its a pretty simple clone.

 1 class Person
 2   named: (name) ->
 3     @name = name
 4     @
 5   withSpouse: (spouse) ->
 6     @spouse = spouse
 7     @
 8   bornOn: (dob) ->
 9     @dob = dob
10     @
11   build : ->
12     return {
13       name: @name
14       spouse: @spouse
15       dob: @dob
16     }
17   console.log new Person().named('Adam').withSpouse('Rachel').build()

But hey, this is coffeescript. We can do better. Lets use a attribute shortcut to reduce the code length.

 1 class Person
 2   named: (@name) ->
 3     @
 4   withSpouse: (@spouse) ->
 5     @
 6   bornOn: (@dob) ->
 7     @
 8   build : ->
 9     return {
10       name: @name
11       spouse: @spouse
12       dob: @dob
13     }
14 console.log new Person().named('Adam').withSpouse('Rachel').build()

I suspect there may be an even cleaner way to do this, but this seems concise enough for now.

The full source code is available here: https://github.com/adamnengland/coffee-fluent-interface

Exit mobile version