Beginner - Fluent Interfaces

· 1 min

So, let’s continue from our last post method chaining with C#!

To recap, Jim 🧔 found a cleaner, more efficient method of building his sandwich, but he’s discovered there should be a specific order to the ingredients.

With method chaining we can’t enforce a specific order of methods called. Let’s illustrate this problem.

    class SandwichFactory
    {

        public SandwichFactory AddBread()
        {
            // implementation omitted for brevity
            return this;
        }

        public SandwichFactory AddCheese()
        {
            // implementation omitted for brevity
            return this;
        }

    }

We, as sandwich construction experts, want to enforce the following pattern:

However, a consumer of our SandwichFactory class could do the following:

    var createSandwich = new SandwichFactory()
        .AddCheese()
        .AddBread();

Or something worse! Let’s fix this problem.

Coming up with a nice fluent API requires a good bit of thought - Martin Fowler

Depending on the API we want to provide, complexity can rapidly escalate. For our example, we’re going to keep this small to illustrate the concepts more than application. Let’s provide our solution below and go through the reasoning behind decisions made in regards to fluent interfaces:

        public sealed class SandwichFactory : ISandwichBread, ISandwichCheese
        {
            private SandwichFactory()
            {
            }

            public static ISandwichBread Create => new SandwichFactory();

            public ISandwichCheese AddBread()
            {
                throw new NotImplementedException();
            }

            public ISandwichBread AddCheese()
            {
                throw new NotImplementedException();
            }
        }

        public interface ISandwichBread
        {
            ISandwichCheese AddBread();
        }

        public interface ISandwichCheese
        {
            ISandwichBread AddCheese();
        }

Consuming the SandwichFactory API, we now can’t add cheese 🧀 before bread 🍞, since our design enforces a bread > cheese hierarchy.

        SandwichFactory.Create
            .AddBread()
            .AddCheese()
            .AddBread();

Simples! 💪