LINQ is clearly gaining a fair amount of traction, given the number of posts I see about it on Stack Overflow. However, I've noticed an interesting piece of coding style: a lot of developers are using query expressions for every bit of LINQ they write, however trivial.
Now, don't get the wrong idea - I love query expressions as a helpful piece of syntactic sugar. For instance, I'd always pick the query expression form over the "dot notation" form for something like this:
from line in new LineReader(file)
let entry = new LogEntry(line)
where entry.Severity == Severity.Error
select file + ": " + entry.Message;
(Yes, it's yet another log entry example - it's one of my favourite demos of LINQ, and particularly Push LINQ.) The equivalent code using just the extension methods would be pretty ugly, especially given the various range variables and transparent identifiers involved.
However, look at these two queries instead:
where person.Salary > 10000m
select person;
var dotNotation = people.Where(person => person.Salary > 10000m);
In this case, we're just making a single method call. Why bother with three lines of query expression? If the query becomes more complicated later, it can easily be converted into a query expression at that point. The two queries are exactly the same, even though the syntax is different.
My guess is that there's a "black magic" fear of LINQ - many developers know how to write query expressions, but aren't confident about what they're converted into (or even the basics of what the translation process is like in the first place). Most of the C# 3.0 and LINQ books that I've read do cover query expression translation to a greater or lesser extent, but it's rarely given much prominence.
I suspect the black magic element is reinforced by the inherent "will it work?" factor of LINQ to SQL - you get to write the query in your favourite language, but you may well not be confident in it working until you've tried it; there will always be plenty of little gotchas which can't be picked up at compile time. With LINQ to Objects, there's a lot more certainty (at least in my experience). However, the query expression translation shouldn't be part of what developers are wary of. It's clearly defined in the spec (not that I'm suggesting that all developers should learn it via the spec) and benefits from being relatively dumb and therefore easy to predict.
So next time you're writing a query expression, take a look at it afterwards - if it's simple, try writing it without the extra syntactic sugar. It may just be sweet enough on its own.
...Full Article.
No comments:
Post a Comment
Post your comments here: