简体   繁体   中英

Is it bad practice for a class method to return `this`?

public class Chain
{
    public string ChainString;

    public Chain() 
    {
        ChainString = "{}"; 
    }

    public Chain AddLink()
    {
        ChainString += "-{}";
        return this; // is this a bad idea?
    }
}

In the above example, the AddLink method returns the this . The reason I want to do this is for a more readable instantiation, like below.

// more verbose (here, `AddLink` returns void)
Chain myChain = new Chain();
myChain.AddLink();
myChain.AddLink();
myChain.AddLink();
// myChain.ChainString = "{}-{}-{}-{}"
// nicer
Chain myChain = new Chain()
    .AddLink()
    .AddLink()
    .AddLink();
// myChain.ChainString = "{}-{}-{}-{}"

Is there any reason I shouldn't do this? I can't think of any, but it feels a bit hacky and I've not seen it done elsewhere.

No. This is a common pattern for fluent interfaces .

This is fine. May I also suggest:

public Chain AddLink(int links = 1)
{
    if (links <= 0) return this;

    string link = "-{}";
    var buf = new StringBuilder(ChainString, ChainString.Length + (links * link.Length));
    for(int i=0; i<links; i++)
    {
        buf.Append(link);
    }

    ChainString = buf.ToString();
    return this; 
}

As posted above, this a very common design pattern that aims to make code more readable. You might find several terms employed to describe such a code (fluid coding, fluent style, fluent api, fluent interface). On the other hand it is difficult or sometimes even impossible to debug. Intermediate results are unattainable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM