Martin Fowler recently posted about Fluent Interface. Fluent Interface is about performing the task fluently and in a more natural manner

Martin Fowler recently posted about Fluent Interface. Fluent Interface is about performing the task fluently and in a more natural manner. Take a look at the following code:

  CustomCategory category = new CustomCategory() { Name = "Fiction Books" };
            category.Books.Add(new CustomBook() { Name = "Adventures of Spiderman" });
            category.Books.Add(new CustomBook() { Name = "Robot man" });

In the above code I am simply adding a Category and then adding books to the Category. The Category has one-to-many relationship with the books. You can see that I had to write two lines to add two books to a category. A more natural way of adding the books using the Fluent Interface would be:

// Add three books
            category.Books.AddBook
                (new CustomBook() { Name = "Superman" })
                .AddBook(new CustomBook() { Name = "Spiderman" })
                .AddBook(new CustomBook() { Name = "Batman" })
                .AddBook(new CustomBook() { Name = "catwoman" });


Here I am adding one book after the other in a more natural way.

Here is another sample where I am dealing with Person and his Accounts.

 Person person = new Person() { Name = "Mohammad Azam" };

            person.Accounts.AddAccount(new Account() { Name = "WWW", Balance = 500 })
                .AddAccount(new Account() { Name="WAMU", Balance=50 });

            person.Accounts[0].Deposit(200).Withdraw(1000);


In the above example I am first adding a bank account to a Person and then executing the Deposit and Withdraw method on the account.