Thursday, December 29, 2005

Fluent Interfaces

I'd like to add to Paul's and Mike's posts regarding fluent interfaces.

I very much agree with them that this kind of method chaining allows to create very readable and intuitive interfaces. The million dollar question is when to actually use this kind of programming style.

Of course there are no definitive answers but I suggest to consider the following points:
a) Use your intuition. If you don't feel this will address the 95% of common use-case for using your interface, then it's probably not the right solution for what you're trying to accomplish.
b) As Paul noted, if in the common use-case you don't have all the necessary data available to complete the task in one go, you should think twice about doing it.
c) Probably the most important point: It really has to read well in your language (e.g. English), preferably as a complete sentence. If you can't read the code out aloud then it's probably not what you want. This is a good example of what I think reads well:

$sms->to("1650939202")
->
from("14082924021")
->
message("Will meet you at 8pm")

->
send()
;

d) You will usually want some form of error handling for your code. This kind of syntax pretty much forces you to use exception based error handling. Make sure that this suits your needs and application architecture.

Do you have any other suggestions for guidelines? I'd be happy to hear them.