In this article I’m gonna explain the Fluent interface and Builder coding patterns and how to use them together to make clean and elegant code in your applications.

We will create a sample project using both patterns. You can follow the article step by step, download the project code from my public repository at BitBucket for git users, or just download the .ZIP file using this link, and start fiddling with it right away .

The Fluent interface pattern

The fluent interface pattern is used to make code more readable and easy to understand. It’s based in using the same context passed as return value so it can be used again for the next action, generating a method-cascading sentence.

The general context of a fluent interface should be:

  • Defined by the return value of the called method.
  • Self-referential, where the new context is equivalent to the last context.
  • Terminated through the return of a void context.

The Builder pattern

The builder pattern allows us to separate an object from the code that builds it. It’s used for building complex objects or groups of them.

Using this pattern we avoid creating multiple constructors for the class that would lead us to the telescoping constructor anti-pattern (having lots of different constructors for a single complex object) that makes code harder to read and understand.

Normally we will need the object class itself, a builder class, and eventually, a director class for complex multi-object constructions.

Mix it up!

Mixing the two patterns, we can achieve a very nice and elegant code for object creation, that should lead to something like this:

Square mySquare = new PolyShapeBuilder<Square>()
            .SetX(100)
            .SetY(100)
            .SetColor(Color.Blue)
            .SetFillColor("#FFFF00")
            .AddVector(new Vector(90, 100))
            .AddVector(new Vector(90, 100))
            .AddVector(new Vector(90, 100))
            .Build();

Nifty, eh? Okay, let’s start with it

Let’s do it!

First of all we will create our class interface for a Polygon Shape:

public interface IPolyShape
{
    int X { get; set; }
    int Y { get; set; }
    Color Color { get; set; }
    Color FillColor { get; set; }
    bool Closed { get; set; }
    List<Vector> Vectors { get; set; }
}

Then, we start with our builder class. We’ll make a generic class so we can create or pass it any IPolyShape object without problem:

  
public class PolyShapeBuilder<T> where T : IPolyShape, new()
{
    private T _shape;

    public PolyShapeBuilder(T shape)
    {
        _shape = shape;
    }

    public PolyShapeBuilder() : this(new T()) { }
}

Ok, let’s split this… our builder has a private field of type T. This is the field with the object we are going to “decorate” or change using the class methods, and will be the result when we finish the build task.

Note also we have two constructors.  The first one will take an already created object so we can change any of their properties, the second one is the default parameterless constructor that just instantiates a fresh new object and calls the first one.

Now is time to add the decorator methods. They change properties from our internal object and return the same builder as context, following the Fluent interface method so we can chain a new call:

public PolyShapeBuilder<T> SetY(int y)
{
    _shape.Y = y;
    return this;
}

Doing this in all the decorator methods, allows us to use the return as start for the next call.

All the builders, as their name says, must finish building the object, and all Fluent interfaces should finish in a void call breaking the method chain. The best way of mixing the two patterns then, is making our Build() method to return the final object, finishing the builder chain like this:

public T Build()
{
    return _shape;
}

The Square class

For testing purposes, we’ll create a Square class implementing IPolyShape:

public class Square : IPolyShape
{
    public int X { get; set; }
    public int Y { get; set; }
    public Color Color { get; set; }
    public Color FillColor { get; set; }
    public bool Closed { get; set; }
    public List<Vector> Vectors { get; set; }

    public Square()
    {
        Closed = true;
        Vectors = new List();
    }
}

Finishing the application and running

Now we create the main program class in console application like this:

static void Main(string[] args)
{
    Square mySquare = new PolyShapeBuilder<Square>()
        .SetX(100)
        .SetY(100)
        .SetColor(Color.Blue)
        .SetFillColor("#FFFF00")
        .AddVector(new Vector(90, 100))
        .AddVector(new Vector(90, 100))
        .AddVector(new Vector(90, 100))
        .AddVector(new Vector(90, 100))
        .Build();

    Console.WriteLine(
        string.Format("We have here a nice Square with {0} vectors, "+
                        "positioned at {1},{2} in {3} color with {4} background!",
                    mySquare.Vectors.Count(), 
                    mySquare.X,
                    mySquare.Y,
                    mySquare.Color.Name, 
                    mySquare.FillColor.Name));

    Console.ReadLine();

}

You should get this output at runtime:
We have here a nice Square with 4 vectors, positioned at 100,100 in Blue color with ffffff00 background!

Thank you!

And that’s all!!!

I hope this little article can help you making cleaner and more understandable code. I will be happy with that!

Don’t forget to add the references to System.Drawing for the Color class if you used it, or just download the project from any of this links:

Git from Bitbucket
Zip file

Follow me

Joan Vilariño

Senior .NET Developer at Ohpen
Developer for more than 25 years and IT, gadget, mobile and electronics enthusiast working and publishing from Barcelona.
Follow me