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.

class Person

  named: (name) ->
    @name = name
    @

  withSpouse: (spouse) ->
    @spouse = spouse
    @

  bornOn: (dob) ->
    @dob = dob
    @

  build : ->
    return {
      name: @name
      spouse: @spouse
      dob: @dob
    }

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.

class Person
  
  named: (@name) ->
    @

  withSpouse: (@spouse) ->
    @

  bornOn: (@dob) ->
    @

  build : ->
    return {
      name: @name
      spouse: @spouse
      dob: @dob
    }

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

Advertisements
Tagged

One thought on “Fluent Interfaces in Coffeescript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: