Can a C# method chain be “too long”?

前端 未结 4 2091
青春惊慌失措
青春惊慌失措 2021-02-05 05:57

Not in terms of readability, naturally, since you can always arrange the separate methods into separate lines. Rather, is it dangerous, for any reason, to chain an excessively l

4条回答
  •  一个人的身影
    2021-02-05 06:53

    Readability is the biggest concern, but often that isn't a problem at all.

    You could also describe LINQ query syntax as (underneath it all) exactly such a setup. It just makes it look prettier ;-p

    One possible issue is where you need to introduce things like using or lock; with the fluent API you may be tempted to simply drop these components, but that might lead to oddities when an exception is thrown.

    The other possible thought is that you might want to have more granular exception handling around some of the calls; but you can always just break the flow:

    var foo = bar.MethodA().MethodB(...).MethodC();
    try {
        foo.MethodD();
    } catch (SomeSpecificException) {
        //something interesting
    }
    

    Or you could even do that in an extension method to keep the fluent appearance:

    bar.MethodA().MethodB(...).MethodC().MyExtensionMethodD();
    

    where MyExtensionMethodD is the one you add with special handling (exceptions, locks, using, etc).

提交回复
热议问题