How to ensure the sequence of methods in fluent API?

蹲街弑〆低调 提交于 2019-12-22 10:39:34

问题


I want to create fluent interface for some of my classes that I am building as part of a framework. I have created the methods and I am able to successfully chain methods. Now I want to ensure that I can handle the improper sequence of method calls.

The thing I am doing is something like CreateWorkflow -> OpenConfiguration -> ChangeUserName In the above scenario it wouldn't make sense if ChangeUserName was called first because it is dependent on OpenConfiguration.

I am confused whether I am correct in creating a Fluent chain of methods for this scenario or not and how to make the sequence work. To me this scenario seems to be very suitable for creating a fluent API.


回答1:


Here is the sample code that enforces method chain in specific order. I've used the example from here and fixed a minor issue in the original code. Here is the running code in dotnet fiddler

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; }


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

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

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



回答2:


The real key is if you require a specific sequence for a fluent API to work you API needs improvement. Maybe you should consider something a little different. If ChangeUserName needs OpenConfiguration the consumer of the API shouldn't care. Either internalize the dependency so the API becomes:

CreateWorkflow -> ChangeUserName

or if the consumer already has the Configuration Object you could use a Dependency Injection approach and make the API something like:

CreateWorkflow(IConfigurationManager) -> ChangeUserName

or

CreateWorkflow -> ChangeUserName(IConfigurationManager)

I show 2 approaches here as I am not sure what the scope of dependency is on your configuration class. By either internalizing the need or adding a required parameter onto the signature of one of the methods you should be able to eliminate the fixed sequence issue. Other than a clear "Start" and "Finish" to your API.

Hope this helps.



来源:https://stackoverflow.com/questions/25019128/how-to-ensure-the-sequence-of-methods-in-fluent-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!