Fluent interfaces introduction and sample.

Learning how to write a fluent interface can help when you want to write the next ORM or if you just wonder how to concatenate your methods in a LINQ style. I’m particularly interested in using this technique to write Html helpers. Anyway, let see a basic example.

A simple calculator class/interface , using a fluent interface:

Code Snippet
public interface IFluentCalcolator
{
    IFluentCalcolator Init(decimal number);
    IFluentCalcolator Add(decimal number);
    IFluentCalcolator Substract(decimal number);
    IFluentCalcolator Multiply(decimal number);
    IFluentCalcolator Divide(decimal number);
    decimal Result();
}

public class FluentCalculator : IFluentCalcolator
{
    private decimal _initialValue = 0;
    public IFluentCalcolator Init(decimal number)
    {
        _initialValue = number;
        return this;
    }

    public IFluentCalcolator Add(decimal number)
    {
        _initialValue += number;
        return this;
    }

    public IFluentCalcolator Substract(decimal number)
    {
        _initialValue -= number;
        return this;
    }

    public IFluentCalcolator Multiply(decimal number)
    {
        _initialValue *= number;
        return this;
    }

    public IFluentCalcolator Divide(decimal number)
    {
        _initialValue /= number;
        return this;
    }

    public decimal Result()
    {
        return _initialValue;
    }   
}

And here’s how to use it, the method concatenation looks coolWinking smile

Code Snippet
[Test]
public void FluentCalculator_Test()
{
    var fluentCalcolator = new FluentCalculator();
    var result = fluentCalcolator.Init(10).Add(10).Divide(4).Multiply(5).Result();
    Assert.True(result == 25);
}




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *