Keep It Simple

228 words

Ran into another post from our MVP friend Dan Wahlen: How Would You Refactor this Code? #1. I don’t normally respond to these kinds of things because it always devolves into a my-code-is-bigger-than-your-code conversation (if you know what I mean, wink, wink, nudge, nudge). But this post struck me because, again, Mr. Wahlen is using new wizbang C# 3.0 language features for no particular reason. He seems to be finding ways to shoehorn new language features into solutions that would otherwise work perfectly fine using regular old C# 2.0 features.

But on to the refactoring. Here’s his code snippet:

string name = “mc_gross_1”; //The prefix and number are variable
string[] cartNames = { “item_number_", “item_name_", “mc_gross_", “quantity_" };
if (cartNames.Where(p => name.StartsWith(p)).Count() > 0)
{
  //process name
}

I like to know what code is doing at a glance, but it’s not terribly obvious what that’s doing without comments or study. So first I would want to move the arcane C# 3.0 stuff into a clearly-named function. In this case an Extension method to extend the string object seems like a good idea. The end result might look something like this:

if( name.StartsWithAny( cartNames ) ) { }

That’s much easier to grasp. The actual implementation of StartsWithAny() doesn’t make much difference, but I certainly wouldn’t use Lambdas, LINQ, or Regex. What’s wrong with, you know, a loop?

Originally posted on my personal blog which was active from 2003 to 2020.

Sorry, new comments are disabled on older posts. This helps reduce spam. Active commenting almost always occurs within a day or two of new posts.