Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent Interfaces Implementation

In order to make my code more organized i have decided to use fluent interfaces; However by reading the available tutorials i have found many ways to implement such fluency, among them i found a topic who says that to create Fluent Interface we should make use of Interfaces, but he did not provided any good details in order to achieve it.

Here is how i implement Fluent API

Code

public class Person
{
    public string Name { get; private set; }
    public int Age { get; private set; }

    public static Person CreateNew()
    {
        return new Person();
    }

    public Person WithName(string name)
    {
        Name = name;
        return this;
    }

    public Person WithAge(int age)
    {
        Age = age;
        return this;
    }
}

Using The Code

Person person = Person.CreateNew().WithName("John").WithAge(21);

However, how could i involve Interfaces to create Fluent API in a more effective way ?

like image 373
Roman Ratskey Avatar asked Feb 13 '26 15:02

Roman Ratskey


1 Answers

Implementing fluent API using interface is good if you want to control the sequence of the calls. Let's assume that in your example when name is set you also want to allow to set age. And lets assume on top of that you need to save this changes as well, but only after when the age is set. To achieve that you need to use interfaces and use them as return types. See the example :

public interface IName
{
    IAge WithName(string name);
}

public interface IAge
{
    IPersist WithAge(int age);
}

public interface IPersist
{
    void Save();
}

public class Person : IName, IAge, IPersist
{
    public string Name { get; private set; }
    public int Age { get; private set; }

    private Person(){}

    public static IName Create()
    {
         return new Person();
    }
    public IAge WithName(string name)
    {
        Name = name;
        return this;
    }

    public IPersist WithAge(int age)
    {
        Age = age;
        return this;
    }

    public void Save()
    {
        // save changes here
    }
}

But still follow this approach if it is good/needed for your specific case.

like image 132
Incognito Avatar answered Feb 16 '26 05:02

Incognito



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!