10
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.

doliphin
  • 752
  • 6
  • 22

3 Answers3

15

No. This is a common pattern for fluent interfaces.

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
0

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; 
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

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.

Benzara Tahar
  • 2,058
  • 1
  • 17
  • 21
  • how so? You can easily step in / step out when dealing with this idiom and see every intermediate result. – bolov Feb 02 '21 at 22:21
  • Imagine using a fluent library and you chain in a single instruction 10 fluent calls. First you can't step in/out any of the fluent method calls since it's an external code and if one fluent call in the chain fails then the whole sequence fails and it's not at least straight forward to debug/find the issue – Benzara Tahar Feb 02 '21 at 22:28
  • not being able to debug an external library is not particular to chaining. – bolov Feb 02 '21 at 23:06