Creating Readable LINQ
Keith Elder wrote a post a post asserting (or at least proposing) that a more imperative syntax for a problem is more readable than a LINQ based C# 3.0 version. (See here for his post). Well, that got my hackles up. Some days, my hackles get up before I do, but I digress.
His example code as examining IP addresses for a machine. His poor example was this:
1: string ipAddy = Dns.GetHostAddresses(Dns.GetHostName()).Single(i => ValidateIP4Address(i.ToString())).ToString();
(ValidateIP4Address is shown in Keith’s example, and is not repeated here).
I’ll agree with Keith on one point: that’s ugly code. Formatting is only part of it. It’s also not leveraging one of the features that make LINQ readable: query expressions. It uses two different conversions from each IP address to a string. Much of the core logic is hidden.
Let’s try this instead:
1: var ipAddy = (from address in Dns.GetHostAddresses(Dns.GetHostName())
2: let addressLabel = address.ToString()
3: where ValidateIP4Address(addressLabel)
4: select addressLabel).First();
The first line of the query defines the source: Host addresses.
The second line defines a local variable to cache the string representation of the address.
The third line defines the filter condition: A valid IP4 address.
And the fourth line defines the result: A single string, the first in the sequence
I’ll agree that if you haven’t looked at LINQ code very much, this can still appear hard to read. But that’s a short-term argument: If you’re reading my blog, you're a developer, and you should be learning new features in whatever language you are using.
Some of Keith’s concerns are very valid: pulling out the latest new features just to use them and experiment with whatever looks interesting will create bad code. But there is a lot to be gained by using the new features carefully, and adding them in the appropriate manner, and following the best idioms for the newer features.
There’s plenty of resources to help you. Use them, and discuss readability with your peers. It’s the only way you’ll know what other developers will understand.