Using a lambda expression versus a private method

2019-03-11 01:28发布

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

Action<Exception> logAndEat = ex => 
{  
    // Log Error and eat it
};

try
{
    // Call to a WebService
}
catch (SoapException ex)
{
    logAndEat(ex);
}
catch (HttpException ex)
{
    logAndEat(ex);
}
catch (WebException ex)
{
    logAndEat(ex);
}

My question is: what is the advantage (if any) of using a lambda expression for LogAndEat as opposed to the (in my view simpler and more obvious) private method as follows:

private void LogAndEat(Exception ex)
{
    // Log Error and eat it
}

Edit: Thanks for the answers so far but just restating my fundamental question a little more clearly: which approach is better/would you recommend in this instance? A lambda expression or a private method?

标签: c# .net lambda
7条回答
Deceive 欺骗
2楼-- · 2019-03-11 01:56

To understand whether it's better to use a lambda expression (as I did in the original answer) or use a 'proper' method, we need to make a decision based on how reusable the common error handling code is.

  • If the common error handling code is completely reusable by other functions in different classes across the application, then it should probably be an internal or public function, which may be in a different class if that makes the code organisation more sensible.

  • If the common error handling code is reusable by other function in the same class only, then it should probably be a private function in the same class.

  • If the common error handling code is not reusable by any other function, and should only ever be used by this particular function, then you have two choices. The first is to use a delegate to encapsulate it within the boundaries of the function, ensuring that the function does not leak any implementation details. The second is to use a private function in the same class with a comment that it should only be called by the function it is intended for.

In the third case, there is no clear 'best way' to do it as both are perfectly legitimate ways to achieve the same goal. My tendency would be to use a delegate when the common code is small and/or you need some of the behaviour of delegates like capturing variables.

Now, coming back to the question, why I wrote the code using a delegate? I had no information about whether the error handling code was re-usable, so I assumed that it was not, and decided to use a delegate as I figured people would find it easy to go from this to realising it could be a 'proper' method (as you have) whereas if I showed use of a 'proper' function people may not realise that a delegate would be an alternative.

查看更多
登录 后发表回答