Friday, May 1, 2015

Build your class like fluent API

Fluent API is modern programming style where you can strictures your code in more semantic way. If you have used JQuery functions or LINQ query then you have notion of Fluent API. Yes, the structure is something like this.

DoThis(“This is ”).AndThis(“It’s too important”).AtLast(“This”);

Now, what is advantage of this style ? We could implement it by creating object of respective class and set 3 properties one by one. Which is something similar to this.

MyClass Obj = new MyClass();
Obj.DoThis= “”
Obj.AndThis=””
Obj.AtLast = “”

Now, let’s compare both style. We are seeing that the first approach is taking less line and it’s kind of human readable English. So, a non programmer or half programmer guy too able to understand the meaning.

Ok, now let’s create our own fluent API, the code sample shown below.

public class Person
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public string Gender { get; set; }

        public Person HisName(string name)
        {
            this.Name = name;
            return this;  
        }
        public Person HisSurname(string surname)
        {
            this.Surname = surname;
            return this;
        }
        public Person HisGender(string gender)
        {
            this.Gender = gender;
            return this;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.HisName("Sourav").HisSurname("Kayal").HisGender("Male");

            Console.WriteLine("Name : "+  p.Name +  " " + p.Surname  + " - Gender: " + p.Gender);
            Console.ReadLine();
        }
    }

Have a look on value initial style in Person class just we are chaining method instead of setting property one by one.




  

No comments:

Post a Comment