«
jQuery Delay Function |
Friday Links #54 »
I’m surprised at how much code I review that still does not take advantage of the newer constructs of C#. Here’s an (admittedly contrived) example.
static void Main()
{
var names = new[] { "name1", "name2", "name3", "name4", "name5", "name6", "name7" };
var count = 0;
foreach (var name in names)
{
if (name.Contains("name"))
count += 1;
}
Console.WriteLine(count);
}
Now compare it to this.
static void Main()
{
var names = new[] { "name1", "name2", "name3", "name4", "name5", "name6", "name7" };
Console.WriteLine(names.Count(name => name.Contains("name")));
}
Which would you prefer to maintain? Which one more clearly communicates the intent of the program?
If that’s not enough to convince you, consider that extension methods like Count() are static, which allows for further optimizations and parallel execution opportunities.
If you consider yourself a pro, you owe it to yourself (and your fellow developers) to keep on top of these things. Read books, pair program, embrace the changes and learn from others. People smarter than you and I have spent countless hours thinking about these things and improving them. Shouldn’t you take advantage of those efforts?
Comments
RE: Improving your code with LINQ and Lambdas
by Brad
Monday, June 08, 2009 10:07 AM
Just because its new and uses less code doesn't make it better. In fact, the majority of the straight line corporate developers that I've come across would much rather see option one. It is much easier to debug (setting break points and F10ing through is easier) and that means everything if you are trying to maintain someone else's code.
We've made the var keyword illegal unless they are absolutely necessary. You should declare your types as much as possible.
One of the things that us professional developers fail to realize is that 90% of the coding that takes place in corporate America is maintenance. Its important for system developers to write code that is easy for other programmers to debug. F10 step over) is a critical need.
RE: Improving your code with LINQ and Lambdas
by Mike
Monday, June 08, 2009 10:15 AM
Brad, I think you missed the point. It's not because it's new that it's better. The code is more concise and communicates more clearly its intent. And it can take advantage additional optimizations built into the framework. It's not a trick in this case, it's simply better code. Finally, programming down to the lowest common denominator as you suggest is not a good idea imho. Mediocrity breeds mediocrity.
powered by Bloget™