Writing Fluent API in your applications

Fluent Interfaces / APIs are an amazing way of chaining methods and passing the input of the previous operation to the next operation. This reduces the amount of code required to declare similar objects or setting properties and configurations of the same object and makes the code more readable. Martin Fowler and Eric Evans coined the term back in 2005 (http://martinfowler.com/bliki/FluentInterface.html)

The implementation is very straight forward. The general pattern is to have chained methods each of which should be self-referential (should return object of its own type) and a terminating method to end the chain.

Following is a simplest example, a Number class which provides self-referential methods of operations returning the Number Object itself and an Equals method to terminate the chain.

    public class Number

    {

        private int _number;

        public Number(int num)

        {

            _number = num;

        }

        public Number Add(int num)

        {

            _number += num;

            return this;

        }

        public Number Subtract(int num)

        {

            _number -= num;

            return this;

        }

        public Number Multiply(int num)

        {

            _number *= num;

            return this;

        }

        public Number Divide(int num)

        {

            _number /= num;

            return this;

        }

        public int Equals()

        {

            return _number;

        }

    }

So, we can use the number class as follows by chaining the operations together.

              Console.WriteLine(

                new Number(10)

                .Add(10)

                .Subtract(5)

                .Multiply(10)

                .Divide(2)

                .Equals()

                );

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s