Sunday, August 18, 2013

C# Design pattern interview questions: - What are fluent interfaces and method chaining?

Fluent interfaces simplify your object consumption code by making your code more simple, readable and discoverable.

So for instance let’s say you have a customer class with properties like “FullName” , “Dob”, and “Address”. If you want to consume the class you would write something as shown below.

Customer customer = new Customer();
customer.FullName = "Shiv";
customer.Dob = Convert.ToDateTime("1/1/2008");
customer.Address = "Mumbai";

But if you use fluent interfaces your client consumption code can be simplified as shown below.

customer.NameOfCustomer("Shiv")
                .Bornon("12/3/1075")
                .StaysAt("Mumbai");


So how to implement Fluent interfaces?

One of the most common way of implementing fluent interface is by using “Method Chaining”. For example below is a simple “Customer” class and let’s say we want to implement fluent interface on the top of it.

public class Customer
    {
        private string _FullName;

        public string FullName
        {
            get { return _FullName; }
            set { _FullName = value; }
        }

        private DateTime _Dob;

        public DateTime Dob
        {
            get { return _Dob; }
            set { _Dob = value; }
        }

        private string _Address;

        public string Address
        {
            get { return _Address; }
            set { _Address = value; }
        }
  
    }

So we can use method chaining. 

“Method chaining” is a common technique where each method returns an object and all these methods can be chained together to form a single statement.

So the above customer class we can wrap in another class (“CustomerFluent”) which will implement method chaining and expose chained methods in a simplified format.

So you can see in the below code methods “NameofCustomer” , “BornOn” accept input s and return backs “CustomerFluent” class.

public  class CustomerFluent
    {
        private Customer obj = new Customer();
        public CustomerFluent NameOfCustomer(string Name)
        {
            obj.FullName = Name;
            return this;
        }
        public CustomerFluent Bornon(string Dob)
        {

            obj.Dob = Convert.ToDateTime(Dob);
            return this;
        }

        public void StaysAt(string Address)
        {
            obj.Address = Address;
           
        }
    }

So now your client code becomes something like below.

customer.NameOfCustomer("Shiv")
                .Bornon("12/3/1075")
                .StaysAt("Mumbai");

You can watch our design pattern interview question videos from questpond.com

  

No comments: