Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Fluent interface and method chaining – A good programming approach

This article is about fluent interface and method chaining in C#, a good programming approach.

I just thought to post an article on how we can do programming with nice and fluent approach. Of course this is one of the way, I'm explaining this using chaining methods with interfaces.

This is called fluent interface . Method chaining is not required. It only potentially improves readability and reduces the amount of source code. It is the core concept behind building a fluent interface . Method chaining is inspired by the cascades feature of the Smalltalk language .

Chaining Methods - A Simple Scenario

Fluent interface and method chaining

Figure 1: Fluent interface and method chaining

Suppose you wan’t to make programmers learn different languages. You will start by defining interface ILearnable and its defination as follows:

public interface ILearnable
{
   ILearnable learn(string language);
   ILearnable code(string langauge);
}

Well, nothing special here. Let us go ahead and create a Learner Class, which implements this interface. The only interesting piece you may find in the Learner class is, all methods are returning a type of ILearnable . As long as our Learner class implements ILearnable, we can return 'this', i.e the current Learner Instance.



    public class Learner:ILearnable
    {
        public string name { get; set; }
        public List<string> languages { get; set; }
        public Learner(string name)
        {
            this.name = name;
            languages = new List<string>();
        }
        public ILearnable learn(string language)
        {
            languages.Add(language);
            Console.WriteLine(language+" language learned");
            return this;
        }
        public ILearnable code(string language)
        {
            if (languages.Contains(language))
                Console.WriteLine(language + " coding done");
            else
                Console.WriteLine(language+" language not known");
            return this;
        }
    }

Now, we are ready to train our programmers fluently. Like:

    class Program
    {
        static void Main(string[] args)
        {
            var learner1 = new Learner("arsalancs");
                learner1.learn(".net").learn("java").learn("php").
                code("php").code("cgi").code(".net");
            Console.ReadLine();
        }
    }

As you can see, we are chaining the method calls, because in each call, we are returning an object of type ILearnable. You'll see what arsalancs is doing in the console.

  • .net language learned
  • java language learned
  • php language learned
  • php coding done
  • cgi language not known
  • .net coding done

Chaining Methods - For Collections

Now, let us do something more interesting. Let us create a couple of extension methods for all collections of ILearnable. We do this by writing an extension method for IEnumerable. If you see, our extension methods are accepting a bunch of learnable learners (read, IEnumerable) and returns the same.

Leave out the Console.WriteLine(), it is there just for some pretty printing.

    public static class LearnableExtensions
    {
        public static IEnumerable<ILearnable>learn(this IEnumerable<ILearnable> learners,  string language)
        {
            foreach (var member in learners)
                member.learn(language);
            Console.WriteLine();
            return learners;
        } 
        public static IEnumerable<ILearnable>code(this IEnumerable<ILearnable> learners, string language)
        {
            foreach (var member in learners)
                member.code(language);
            Console.WriteLine();
            return learners;
        }

    }  

Now, let us create few learners, and train them together :)

    class Program
    {
        static void Main(string[] args)
        {
            var learners = new List<ILearnable>
            {
                new Learner("arsalancs"),
                new Learner("mrbool")
            };
            learners.learn("c#").code("c#");
            Console.ReadLine();
        }
      } 

And you'll see what they are doing, in this order.

  • c# language learned
  • c# language learned
  • c# coding done
  • c# coding done

Why Do We Need Extension Methods?

While designing your classes in .NET projects, we used to have sibling classes which do simple operation from its parent classes to add a kind of customization for parents' methods. Suppose that you want to extend int class in .NET by adding a factorial method to it using recursion technique.

One way of thinking is to inherit int class and add your new method to it and use your new methods in your code. This is a valid solution but let us see what extension methods can provide us.

Using extension methods, you can use your new methods as a part of int class in .NET. An extension method is a special kind of static method that allows you to add new methods to existing types without creating derived types.

The extension methods are called as if they were instance methods from the extended type, For example: x is an object from int class and we called it as an instance method in int class.

In software engineering, a fluent interface (as first coined by Eric Evans and Martin Fowler) is an implementation of an object oriented API that aims to provide for more readable code.

A fluent interface is normally implemented by using method chaining to relay the instruction context of a subsequent call (but a fluent interface entails more than just method chaining). Generally, the context is:

  1. defined through the return value of a called method
  2. self-referential, where the new context is equivalent to the last context
  3. terminated through the return of a void context.

Debugging

Single-line chained statements may be more difficult to debug as debuggers may not be able to set breakpoints within the chain. Stepping through a single-line statement in a debugger may also be less convenient.

Error reporting

Another issue with single-line statements is that it may not be clear which of the method calls caused an exception, in particular if there are multiple calls to the same method making it not obvious which exact call caused a problem.

And finally, Fluent APIs can be used for much more useful tasks . Few fluent API's I've come across.

Hope you liked the article, see you next time.



Assistant System Engineer na Tata Consultancy Services. Bachelor of Technology (B.Tech.), Computer Science na Uttar Pradesh Technical University.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login