流畅的API - 返回这个还是新的?

Rus*_*tam 13 c# java oop design-patterns fluent-interface

我最近提出了一个有趣的问题,流利的方法应该返回什么?他们应该改变当前对象的状态还是创建一个具有新状态的全新对象?

如果这个简短描述不是非常直观,这是一个(不幸的)冗长的例子.这是一个计算器.它执行非常繁重的计算,这就是他通过异步回调返回结果的原因:

public interface ICalculator {
    // because calcualations are too lengthy and run in separate thread
    // these methods do not return values directly, but do a callback
    // defined in IFluentParams
    void Add(); 
    void Mult();
    // ... and so on
}
Run Code Online (Sandbox Code Playgroud)

所以,这是一个设置参数和回调的流畅界面:

public interface IFluentParams {
    IFluentParams WithA(int a);
    IFluentParams WithB(int b);
    IFluentParams WithReturnMethod(Action<int> callback);
    ICalculator GetCalculator();
}
Run Code Online (Sandbox Code Playgroud)

这个接口实现有两个有趣的选项.我将展示它们,然后我会写出我发现它们各自的好坏.

因此,首先是普通,它返回:

public class FluentThisCalc : IFluentParams {
    private int? _a;
    private int? _b;
    private Action<int> _callback;

    public IFluentParams WithA(int a) {
        _a = a;
        return this;
    }

    public IFluentParams WithB(int b) {
        _b = b;
        return this;
    }

    public IFluentParams WithReturnMethod(Action<int> callback) {
        _callback = callback;
        return this;
    }

    public ICalculator GetCalculator() {
        Validate();
        return new Calculator(_a, _b);
    }

    private void Validate() {
        if (!_a.HasValue)
            throw new ArgumentException("a");
        if (!_b.HasValue)
            throw new ArgumentException("bs");
    }
}
Run Code Online (Sandbox Code Playgroud)

第二个版本更复杂,它在每个状态更改时返回一个新对象:

public class FluentNewCalc : IFluentParams {
    // internal structure with all data
    private struct Data {
        public int? A;
        public int? B;
        public Action<int> Callback;

        // good - data logic stays with data
        public void Validate() {
            if (!A.HasValue)
                throw new ArgumentException("a");
            if (!B.HasValue)
                throw new ArgumentException("b");
        }
    }

    private Data _data;

    public FluentNewCalc() {
    }

    // used only internally
    private FluentNewCalc(Data data) {
        _data = data;
    }

    public IFluentParams WithA(int a) {
        _data.A = a;
        return new FluentNewCalc(_data);
    }

    public IFluentParams WithB(int b) {
        _data.B = b;
        return new FluentNewCalc(_data);
    }

    public IFluentParams WithReturnMethod(Action<int> callback) {
        _data.Callback = callback;
        return new FluentNewCalc(_data);
    }

    public ICalculator GetCalculator() {
        Validate();
        return new Calculator(_data.A, _data.B);
    }

    private void Validate() {
        _data.Validate();
    }
}
Run Code Online (Sandbox Code Playgroud)

他们如何比较:

Pro first(this)版本:

  • 更简单,更短

  • 常用的

  • 似乎更节省内存

  • 还有什么?

Pro第二()版本:

  • 将数据存储在单独的容器中,允许分离数据逻辑和所有处理

  • 允许我们轻松修复部分数据,然后填写其他数据并单独处理.看一看:

        var data = new FluentNewCalc()
            .WithA(1);
    
        Parallel.ForEach(new[] {1, 2, 3, 4, 5, 6, 7, 8}, b => {
            var dt = data
                .WithB(b)
                .WithReturnMethod(res => {/* some tricky actions */});
    
            // now, I have another data object for each value of b, 
            // and they have different callbacks.
            // if I were to do it with first version, I would have to create each 
            // and every data object from scratch
            var calc = dt.GetCalculator();
            calc.Add();
        });
    
    Run Code Online (Sandbox Code Playgroud)

在第二版中哪些更好?

  • 我可以像这样实现WithXXX方法:

    public IFluentParams WithXXX(int xxx) {
        var data = _data;
        data.XXX = xxx;
        return new FluentNewCalc(data);
    }
    
    Run Code Online (Sandbox Code Playgroud)

    并使_data readonly(即不可变),一些聪明的人说是好的.

所以问题是,你认为哪种方式更好,为什么?PS我用过c#但很适用于java.

Ond*_*cek 6

当我试图在我的应用程序设计中回答这样的问题时,我总是考虑在他的应用程序中使用我的代码的人会期望什么.

对于实例来说,采用C#DateTime类型.它是一个结构,因此是不可变的.当你要求时

var today = DateTime.Now;
var tomorrow = today.AddDays(1);
Run Code Online (Sandbox Code Playgroud)

如果你不知道那DateTime是不可改变的,你会期待什么?我不希望今天突然明天,这将是混乱.

至于你的例子,我想象只使用计算器的一个实例处理数字,除非我另有决定.这很有道理,对吗?当我写一个等式时,我不会在新行上写下每个表达式.我将所有内容与结果一起编写,然后跳转到下一行以分离问题.

所以

var calc = new Calculator(1);
calc.Add(1);
calc.PrintCurrentValue(); // imaginary method for printing of a current value of equation
Run Code Online (Sandbox Code Playgroud)

对我来说很有意义.