Fabrice's weblog

Tools and Source

News


Read sample chapters or buy LINQ in Action now!
Our LINQ book is also available on AMAZON

.NET jobs

Emplois .NET

The views expressed on this weblog are mine alone and do not necessarily reflect the views of my employer. The content of this weblog is independent from Microsoft or any other company. transatlantys hot news

Contact

Me

Others

Selected content

Great fluent interface sample: the fluent repeater

I'm not that much a fan of fluent interfaces, but in some cases they are well fit.

A great example is the fluent repeater created by Adrian Aisemberg. It's also a good example if you don't know what a fluent interface is.

Here is sample code that uses it:

Repeat.Call<string>(Save).WithParameters("myfile.txt").UntilSucceeds.Start(10);
Repeat.Call(Ping).PauseBetweenCalls(2000).Start(100);

Some more:

Repeat.Call(Open).InBackgroundThread.At(ThreadPriority.Lowest).
        OnSuccessCall(Opened).OnExceptionCall(Failed).Start();

This could be written in the following way using a non fluent interface:

Repeater repeater = new Repeater();
repeater.Method = Open;
repeater.InBackgroundThread = true;
repeater.ThreadPriority = ThreadPriority.Lowest;
repeater.Success += Opened;
repeater.Exception += Failed;
repeater.Start();

Which version do you prefer?

Comments

Matt Kellogg said:

I'm hoping your question is rhetorical. Would someone honestly prefer the non-fluent interface? I think the best thing that's ever happened to fluent interfaces is intellisense.

# April 24, 2008 11:45 AM

Christophe Menet said:

It's not only a matter of "easy writing", but also a matter of "easy reading"!

When I look at your sample, I clearly prefer the non fluent interface, just because I'm use to it. But if you write it this way:

Repeat

 .Call(Open)

 .InBackgroundThread

 .At(ThreadPriority.Lowest)

 .OnSuccessCall(Opened)

 .OnExceptionCall(Failed)

 .Start();

It becomes much more easy to read and to use! For me at least :)

# April 24, 2008 4:17 PM

Fabrice Marguerie said:

This makes it looks as if people are simply after VB's With syntax:

With new Repeater

.Method = Open

.InBackgroundThread = True

.ThreadPriority = ThreadPriority.Lowest

.Success = Opened

.Exception = Failed

.Start()

End With

In the case of the fluent repeater, the order of the invocations isn't important. It's not like a LINQ query where method calls form an ordered chain of operations:

Books

 .Where(book => book.Title.Contains("LINQ")

 .OrderBy(book => book.Price)

 .Select(book => book.Title)

This seems to mean that a fluent interface is superfluous in the case of the repeater.

BTW, is LINQ's API fluent?

# April 24, 2008 5:10 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)