Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 636
doliphin Avatar asked Feb 02 '21 21:02

doliphin


1 Answers

No. This is a common pattern for fluent interfaces.

like image 117
EricSchaefer Avatar answered Nov 15 '22 19:11

EricSchaefer