Using a lambda expression versus a private method

前端 未结 7 1102
北海茫月
北海茫月 2021-02-02 13:42

I read an answer to a question on Stack Overflow that contained the following suggested code:

Action logAndEat = ex => 
{  
    // Log Error          


        
相关标签:
7条回答
  • 2021-02-02 14:30

    Thanks everyone for the great answers which I have up-voted, but I thought I'd summarize them to try and capture the pros and cons in one answer.

    Pros of using a lambda expression (LE) instead of a private method:

    • A LE is scoped to the method in which it is declared so if it is only used by that method then that intent is made explicit by a lambda expression (even though it is possible to pass out a delegate to the LE, one can still argue the intent of declaring a LE in a method is that the LE is scoped to the method). That is, being explicit in terms of its expected usage.
    • Lambda expressions behave like closures so they can access variables scoped to the method they are declared in. This can be neater than passing lots of parameters to a private method.
    • Variables captured by a LE would otherwise be parameters to a private method and this can be exploited to allow a form of currying.

    Cons of using a lambda expression instead of a private method:

    • Because the LE can access variables scoped to the method in which they are contained, it is not possible to modify code in the calling method while debugging.

    There is also the more subjective issue of maintainability and one could argue that LE are not as well understood by most developers as a private method and thus are somewhat less maintainable. One could also argue that a LE improves maintainability because it is encapsulated in the method in which it is called as opposed to a private method which is visible to the entire class.

    0 讨论(0)
提交回复
热议问题