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

Viewed 220
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.

3 Answers

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.

Related