3 ms·
People should not be so eager to jump to the new functional constructs in C# to proof it can be cool too. There is no shame in imperative programming, it has it
by tinco 14y ago
People should not be so eager to jump to the new functional constructs in C# to proof it can be cool too. There is no shame in imperative programming, it has its own advantages and can be pretty too.
In this case, just using C# a bit more idiomatically can go a long way:
var descriptions = new ArrayList(mylist.Length);
foreach (var foo in myList)
{
if (foo.Description == "") { continue; }
descriptions.Add(foo.Description);
}
return String.Join("\n", descriptions);
The names the author gives to his variables are the first indicator that he just isn't really in a C# mindset.
- noblethrasher 14y agoThe spirit of your code is correct but I think you'll get a runtime error since the inferred type of your iteration variable, foo, will be System.Object. Here's a slightly more idiomatic C# 2.0 (i.e. sans var goodness) ArrayList descriptions = new ArrayList(mylist.Length); foreach (Foo foo in myList) if (foo.Description != "") descriptions.Add(foo.Description); return String.Join("\n", descriptions);
- tinco 14y agoHey, you're right, it would be a compile time error but indeed. I'd rather supply a generic constraint <Foo> to ArrayList than have it be cast to Foo that way (does it even do that automatically?). Also, do you think leaving out the braces is idiomatic? I think it looks really pretty but I don't like it at all, it is too brittle.
- noblethrasher 14y agoEliding the braces does make it a bit less idiomatic I suppose; but in ten years of programming I don't think I've ever been bitten by a bug caused by that style... not even in JavaScript. On the other hand, I think the risk of making the code slightly more brittle is worth it if it makes it much more pleasant to read. Whenever I see a for/foreach followed by a single statement then I know that the code is doing a simple projection (i.e. Select in Linq or SQL parlance). If it’s a for/foreach followed by an if statement followed by some other statement (as in the above code) then I know it’s a simple filter and projection (i.e. Where and Select). But I wanted to illustrate your larger point, which is that C# programmers shouldn’t be so quick to use functional idioms since imperative code can not only look just a pretty, but it’s almost always slightly more performant since it doesn’t imply as many allocations and indirections.