ASP.NET Hosting

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?

2 Comments

  • 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.

  • 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?

Comments have been disabled for this content.