Anonymous Methods / Lambda's (Coding Standards)

帅比萌擦擦* 提交于 2019-12-01 06:45:59

Bear in mind that things have changed a lot since 2.0. For example, consider .NET 4's Parallel Extensions, which use delegates heavily. You might have:

Parallel.For(0, 100, i => 
{
    // Potentially significant amounts of code
});

To me it doesn't matter whether this is a lambda expression or an anonymous method - it's not really being used in the same way that delegates typically were in .NET 2.0.

Within normal LINQ, I don't typically find myself using large lambda expressions - certainly not in terms of the number of statements. Sometimes a particular single expression will be quite long in terms of lines because it's projecting a number of properties; the alternative is having huge lines!

In fact, LINQ tends to favour single-expression lambda expressions (which don't even have braces). I'd be fairly surprised to see a good use of LINQ which had a lambda expression with 5 statements in.

I don't know if having a guideline for short lambda's and delegates is really useful. However, have a guideline for having short functions. The methods I write are on average 6 or 7 lines long. Functions should hardly ever be 20 lines long. You should create the most readable code and if you follow Robert Martin's or Steve McConnell's advice, they tell you to keep functions short and also keep the inner part of loops as short of possible, favorably just a single method call.

So you shouldn't write a for loop as follows:

for (int i = 0; i < 100; i++)
{
    // Potentially significant amounts of code
}

but simply with a single method call inside the loop:

for (int i = 0; i < 100; i++)
{
    WellDescribedOperationOnElementI(i);
}

With this in mind, while I in general agree with Jon Skeet’s answer, I don't see any reason why you shouldn't want his example to be written as:

Parallel.For(0, 100, i =>
{
    WellDescribedPartOfHeavyCalculation(i);
});

or

Parallel.For(0, 100, i => WellDescribedPartOfHeavyCalculation(i));

or even:

Parallel.For(0, 100, WellDescribedPartOfHeavyCalculation);

Always go for the most readable code, and many times this means: short anonymous methods, and short lambda's, but most of all short -but well described- methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!