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

前端 未结 4 2131
青春惊慌失措
青春惊慌失措 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:34

    There are no technical limitations on how long a method chain can be.

    However, three areas that can become problemattic are debugging, exception handling, and resource disposal.

    Debugging is complicated by the same fact that makes chaining so elegant - the lack of intermediate temporary variables. Unfortunately, without temp variables, inspecting intermediate results when debugging becomes painful.

    Exception handling is complicated by the fact that you cannot isolate exceptions raised from one method vs. another. Normally this isn't an issue if you can't do something meaningful in response to the exception - just let it propagate up the call chain. However, if you do realize at a later point that you need exception handling, you have to refactor the chaining syntax to be able to insert appropriate try/catch handlers.

    Similar to exception handling is the case of deterministic disposal of resources. The easiest way in C# to accomplish this is with using() - unfortunately, chaining syntax precludes that. If you are calling methods that return disposable objects, it probably a good idea to avoid chaining syntax so that you can be a good "code citizen" and dispose of those resources as early as possible.

    Method chaining syntax is often a used in fluent APIs, where it allows the syntax of your code to more closely reflect the sequence of operations you intend. LINQ is one example in .NET where fluent/chaining syntax is often seen.

提交回复
热议问题