language-agnosticdesign-patternsoopfluent-interface

Fluent Interfaces - Method Chaining


Method chaining is the only way I know to build fluent interfaces.

Here's an example in C#:

John john = new JohnBuilder()
    .AddSmartCode("c#")
    .WithfluentInterface("Please")
    .ButHow("Dunno");

Assert.IsNotNull(john);

  [Test]
    public void Should_Assign_Due_Date_With_7DayTermsVia_Invoice_Builder()
    {
        DateTime now = DateTime.Now;

        IInvoice invoice = new InvoiceBuilder()
            .IssuedOn(now)
            .WithInvoiceNumber(40)
            .WithPaymentTerms(PaymentTerms.SevenDays)
            .Generate();

        Assert.IsTrue(invoice.DateDue == now.AddDays(7));
    }

So how do others create fluent interfaces. How do you create it? What language/platform/technology is needed?


Solution

  • You can create a fluent interface in any version of .NET or any other language that is Object Oriented. All you need to do is create an object whose methods always return the object itself.

    For example in C#:

    public class JohnBuilder
    {
        public JohnBuilder AddSmartCode(string s)
        {
            // do something
            return this;
        }
    
        public JohnBuilder WithfluentInterface(string s)
        {
            // do something
            return this;
        }
    
        public JohnBuilder ButHow(string s)
        {
            // do something
            return this;
        }
    }
    

    Usage:

    John = new JohnBuilder()
        .AddSmartCode("c#")
        .WithfluentInterface("Please")
        .ButHow("Dunno");