A fluent interface

A funny thing in programming, captured in a term by Martin Fowler and Eric Evans, is fluent interface.

Explained shortly, it is a style in programming which attempts to make your programs (or parts thereof) resemble sentences as you could (but probably seldomly would) have pronounced them in a fairly understandable human language.

It is easier in dynamic languages like Ruby, but it is still possible in a staticly bound world like that of C# – and it is often a fun challenge to design your utility classes or domain logic to use fluent interface! Moreover, it has a legitimate use in implementing internal domain-specific languages because of its resemblance to human language.

A small example of a list converter class using some kind of fluent interface can be seen if you carry on reading below.

The class(es):

The source code above may seem cryptic at first. However, there is a pattern in the fact that another class instance is returned every time the language syntax requires another type of sentence to be “syntactically correct” (human language-wise). The only time this is returned, it is because UnlessItIsNull is sort of an interjected sentence.

We need an example of its usage. It comes in the form of an NUnit test:

Btw, I am aware that the List class already has a ConvertAll<T> method, which esentially does the same. One justification of writing your own class like this could be that your collections come in forms other than List<T>. This class takes an IEnumerable<T>, which is implemented by all collections (that I know of) in .NET.

Posted in c#

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.