Friday, August 29, 2008

Fluent Interfaces

A Fluent Interface is a design construct that makes your interfaces read like natural language instructions.

I kinda like how a little refactoring of method signatures can make an interface much more "interesting", shall we say ? The idea is to make the interface read more like English. So, for ex., instead of

//<>
Aggregator a = new Aggregator();
List l = dao.getfeedFromEurope();
List l1 = dao.getfeedFromAPAC();
List l2 = dao.getfeedFromAmericas();
a.aggregate(l);
a.aggregate(l1);
a.aggregate(l2);
a.setFilterPolicy(FilterPolicy.NonPayingCountries);
a.filter();
List l3 = a.getFeeds();
...


you'll write

Aggregator a = new Aggregator();
...
List l3 = a.aggregate(l).and_aggregate(l1).and_aggregate(l2).filterWith(FilterPolicy.NonPayingCountries);



Neat, isn't it? The Aggregate class methods are self-referential. In the above example, and_aggregate() just calls aggregate() internally. But the goal here is to improve readability of the interface. Of course, like everything else, fluent interfaces can be overused or misused. You can, for ex. make a very verbose interface or worse make all the interfaces fluent.

I had a difficult time explaining this construct to the code reviewers last time. I guess it takes some time getting used to this style.

No comments: