My New Favorite: Fluent Interfaces

I have always been a big fan of the fluent programming style. Lately, I have been using it a lot. For instance, today I built an api to interact with VMWare where you can add new linux or windows machines and configure them fluently. In this post, I am going over an example that I built. The sample is a City Planner city builder. You can add streets and homes to your city. This is the results of the api that we will create.

Let’s start with our city planner. There isn’t much here other than the methods to add a street or a home.

To get started, we need to add some extension methods to start building out our api. Let’s create an extension that can create a street.

This is a standard extension method that hangs of of the City Planner. The one difference that makes all of this work is the return type. The return type is a CityPlanner. If you look back at the methods of the CityPlanner object, you can now call the method again since you have the instance of the Planner that you are working with.

Building a city street is easy ( on a computer), but building a home is a little more challenging. To build that we need to specify how many floors and windows, among other things. Sounds like a candidate for another builder. You can see on the House Planner, there is a method to build the house. One of the parameters is an anonymous function that takes a HouseBulder object and returns a Home. This will allow us to incrementally build our house with the same fluent style.

If you look at the HomeBuilder class, you can see that all of the methods return itself allow you to continue the method chaining.

In the end, we can print out our blueprint for our city.

Welcome to my city!
Streets
	Main Street
	1st Street
Homes
	Home: Floors=3, Windows=0

I enjoy this kind of expressive programming.  I think it is easy on the eyes.  Cheers!

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