Fluent Interfaces in Ruby

I had a chance to look at what Neal Ford had to write on Fluent Interfaces in his book The Productive Programmer.  Granted, I heard him cover it before at one of his presentations at the No Fluff Just Stuff conference in Reston, VA.

Basically, fluent interfaces have setter functions return self (or this in Java).  By doing this, you can chain the setters together into what looks more like a composed english sentence instead of multiple single-line setter statements.  I find it easier to code and read code written in this manner (particularly in the jQuery style).

Sitting here watching Olympic couple’s figure skating with my wife, it seems like the perfect time to put some example ruby code together for this (as well as the Self Yield spell from Paolo Perrotta’s Metaprogramming Ruby):

class Car
    attr_accessor :speed, :wheels, :direction

    def initialize
        self
    end

    def moving_at(mph)
        self.speed = mph
        self
    end

    def with_wheel_count(count)
        self.wheels = count
        self
    end

    def heading_toward(toward)
        self.direction = toward
        self
    end

    def display
        puts "speed is #{speed}"
        puts "moving in direction #{direction}"
        puts "number of wheels is #{wheels}"
    end
end

car = Car.new.moving_at(65).heading_toward("NE").with_wheel_count(4).display

attr_accessor would not have returned the object instance, requiring a different line for each mutator.

Advertisements

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