Sunday 16 October 2011

Fluent Interface Programming in C#



 In software engineering, a fluent interface (as first coined by Eric Evans and Martin Fowler) is an implementation of an object oriented API that aims to provide for more readable code.

       If you’ve already worked with JQuery, then you may be familiar with method chaining as in the below JQuery code snippet, where subsequent method calls are done in the same line.

$("#helloLabel").text("Hello, world!").removeClass("red").addClass("bold").css("color", "yellow");

   Method chaining  is used to implement fluent interface to control the instruction context of a subsequent call. Nevertheless a fluent interface implies more than just method chaining. Generally, the context is

·         defined through the return value of a called method
·         self referential, where the new context is equivalent to the last context
·         terminated through the return of a void context.

        This style is marginally beneficial in readability due to its ability to provide a more fluid feel to the code. However, it can be detrimental to debugging, as a fluent chain constitutes a single statement for which debuggers may not allow setting up intermediate breakpoints, for instance.


        The really cool aspects of fluent interface is the fact that all the methods return the object that we are currently dealing with, which you can then use to call another method. This allows you to do command chaining, where you can perform multiple methods on the same set of elements, which is really neat because it saves you from having to find the same elements more than once.     

       Before beginning with C# implementation of Fluent API, the key points to implement fluent API are,

The methods of interest should
             ·         return the same object type.
             ·         return ‘this’.

        Let’s begin with a simple example to play with fluent interface in C#. Consider the following interface IDraw  which contains two methods conversely Draw()  and Color(). At a plain look it might seems to be an obvious interface unless you’ve noticed that those two methods return the same interface type IDraw  where they fit in. Now this interface is ready for method chaining.

     /// <summary>
    /// Objects that is to be drawn.
    /// </summary>
    public interface IDraw
    {
        IDraw Draw();
        IDraw Color();
    }

Let’s implement this interface in a class  Shape as below,

     /// <summary>
    /// A mere shape class that implements IDraw
    /// </summary>
    public class Shape : IDraw
    {
        public string Name { get; set; }

        /// <summary>
        /// Creates the shape of interest.
        /// </summary>
        /// <param name="name">Shape name</param>
        public Shape(string name)
        {
            this.Name = name;
            Console.WriteLine("{0} is Created", name);
        }

        /// <summary>
        /// Draws the shape. Note here that this method returns "this"
        /// Which is a key for method chaining and thus we can ask our shape
        /// to perform continuous actions.
        /// </summary>
        /// <returns>Current object.</returns>
        public IDraw Draw()
        {
            Console.WriteLine("{0} is Drawn", Name);
            return this;
        }

        /// <summary>
        /// Colors the shape. Note here that this method returns "this"
        /// Which is a key for method chaining and thus we can ask our shape
        /// to perform continuous actions.
        /// </summary>
        /// <returns>Current object.</returns>
        public IDraw Color()
        {
            Console.WriteLine("{0} is Colored", Name);
            return this;
        }
    }

Now we can do the fluent programming.

static void Main(string[] args)
        {
            new Shape("Rectangle")
                .Draw()
                .Color();
            new Shape("Triangle")
                .Draw()
                .Color();
            new Shape("Circle")
                .Draw()
                .Color();
            Console.ReadLine();
        }

           We’ve chained the method calls in the above example. This is achieved as we are returning an object of  type IDraw on each call.  

Now you can do Fluent interface programming !!! Hope this helps…!

2 comments:

  1. Something new to me! We can method chaining with extensions as well. How it differs from extension methods?

    ReplyDelete
  2. Extension methods are available from .net 3.0 onward, where as Fluent API is a traditional programming concept. It can be implemented with the earlier versions of .net too and not just C# or VB. It's language independent. It's like design pattern.

    Any method (Not just extension methods) can be fluent programmed as long as they follow the fluent API rule of thumb that

    1) The return type of the method should be of same type where they fit in.
    2) return the same object.

    Hope this helps....

    ReplyDelete