开发者

Must a "fluent" (or chainable) method be immutable?

Say I have a class with some properties and some methods for manipulating those properties:

public class PersonModel
{
    public string Name { get; set; }
    public string PrimaryPhoneNumber { get; set; }

    public void LoadAccountInfo(AccountInfo accountInfo)
    {
        this.Name = accountInfo.Name;
    }

    public void LoadPhoneInfo(PhoneInfo phoneInfo)
    {
        this.PrimaryPhoneNumber = phoneInfo.PhoneNumber;
    }
}

Typical usage would be:

var model = new PersonModel();
model.LoadAccountInfo(accountInfo);
model.LoadPhoneInfo(phoneInfo);

I think it would be cool to make the methods chainable:

    public PersonModel LoadAccountInfo(AccountInf开发者_如何学JAVAo accountInfo)
    {
        this.Name = accountInfo.Name;
        return this;
    }

    public PersonModel LoadPhoneInfo(PhoneInfo phoneInfo)
    {
        this.PrimaryPhoneNumber = phoneInfo.PhoneNumber;
        return this;
    }

Then usage would be:

var model = new PersonModel()
    .LoadAccountInfo(accountInfo)
    .LoadPhoneInfo(phoneInfo);

But I am not returning a modified "clone" of the passed-in PersonModel object in each of these chainable methods. They are just modifying the original object and returning it (for convenience). To me, this creates an ambiguity because someone calling these methods may assume that they are immutable (i.e. they leave the original object intact but return a modified object).

Does that violate any sort of best practice regarding fluent/chainable interfaces?


Personally I think that immutability and fluent interfaces are separate concerns. It may be that you find immutability in general to be a good thing, a best practice. But this would be whether or not you used a fluent interface.


No, it's perfectly reasonable to mutate the passed object. Fluent NHibernate methods all work that way, (when they modify the FluentConfiguration object, for example).

But it's not a rule either. String is the best example of an immutable object where you can chain a bunch of methods, each of them returning a new instance.


This article suggests that the objects should be immutable. It comes from a functional language perspective.

http://blogs.msdn.com/b/laurionb/archive/2009/02/16/immutable-objects-in-fluent-interfaces-a-lesson-from-functional-programming.aspx

However, looking at Moq as an example, the objects are not immutable.

I don't think that there is a "best practice" here. As @Ray Toal said, they are separate concerns.


Objects are reference type and when you're specifically asking it to "return this" why would you expect it to return something different.

Doesn't violate any best practice. In fact unless you have a reason there is no need to clone an object.


All the charm of the fluent method consists in returning the same modified object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜