Fluent Interfaces


    var result = MyList.Where(l => l.Value > 200).OrderBy(l => l.CreateDate).Take(5).Select(l => l.Item);


    Fluent interfaces solve two programming issues. First, they make the code more readable and easy to understand. This makes it easier to make changes later. It also makes it easier for new developers to get up to speed quickly with your domain’s API.

    Second, fluent interfaces can be used to force the programmer to perform steps in the correct order. If objects are set up with a fluent interface correctly, a programmer will not able to call a method unless the required precursor method has been called first.

    To better illustrate the advantage of a fluent interface, see the code snippets below. The first shows the creation of an order with some order detail lines. The second shows the same process, but implemented using a fluent interface.



    var customer = new Customer();

    var order = new Order(customer);

    OrderLine ol = new OrderLine { ProductId = 111, Quantity = 3 };


    OrderLine ol = new OrderLine { ProductId = 222, Quantity = 4 };


    var orderProcess = new OrderProcessor();




    var customer = new Customer();


           .WithLine(111, 3)

           .WithLine(222, 4)



    The fluent code above takes less time to code and is much easier to read and follow.

    Fluent interfaces require more planning and work to implement. But, the advantages later on are worth it.


    For more information on fluent interfaces:


    Leave a comment