Patterns: Fluent Interface - make your code easier to read

I never heard of the Fluent Interface pattern until I saw a post written by Randy Patterson titled “How to design a Fluent Interface”. When I first saw the title of the post I thought he was talking about design a user interface, but upon further inspection I found out that using the Fluent Interface pattern in your code will make it easier to read.

Randy posts an example of how to use the Fluent Interface pattern, but I thought I would also write up a short example. My example below shows how to implement a small class to generate Sql scripts using the Fluent Interface pattern.

Example Usage

SQLQuery sql = new SQLQuery();

sql.Select("Id")
   .Select("FirstName")
   .Select("LastName")
   .From("Person")
   .Where("Id = 1")
   .Where("FirstName = 'Chris'")
   .OrderBy("LastName")
   .OrderBy("FirstName");
/// Get the string representation of our Sql query

string strSqlString = sql.ToString();

Console.WriteLine(strSqlString);

Code for the SQLQuery class

public class SQLQuery
{
    private ArrayList _SelectItems = new ArrayList();
    private ArrayList _WhereItems = new ArrayList();
    private ArrayList _OrderByItems = new ArrayList();
    private string _FromTable = null;

    public SQLQuery Select(string select)
    {
        _SelectItems.Add(select);
        return this;
    }

    public SQLQuery From(string from)
    {
        _FromTable = from;
        return this;
    }

    public SQLQuery Where(string where)
    {
        _WhereItems.Add(where);
        return this;
    }

    public SQLQuery OrderBy(string orderby)
    {
        _OrderByItems.Add(orderby);
        return this;
    }

    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("SELECT ");
        for (int i = 0; i < _SelectItems.Count; i++)
            sb.Append(_SelectItems[i] + ((i == _SelectItems.Count - 1) ? " " : ", "));

        sb.Append("FROM ");
        sb.Append(_FromTable);

        sb.Append(" WHERE ");
        for (int i = 0; i < _WhereItems.Count; i++)
            sb.Append(_WhereItems[i] + ((i == _WhereItems.Count - 1) ? " " : " AND "));

        sb.Append("ORDER BY ");
        for (int i = 0; i < _OrderByItems.Count; i++)
            sb.Append(_OrderByItems[i] + ((i == _OrderByItems.Count - 1) ? " " : ", "));

        return sb.ToString();
    }
}

Conclusion

As you can see the Fluent Interface pattern is rather simple to implement and it can really make your code easier to read.

Chris Pietschmann
Chris Pietschmann
Microsoft MVP | App Innovation Leader | Azure, AI & DevOps Architect | HashiCorp Ambassador | Author
I'm a Practice Leader, App Innovation specialist, solution architect, developer, SRE, trainer, and author with 25+ years of experience helping enterprises turn AI, app modernization, cloud architecture, and DevOps into real business outcomes.