Friday, September 19, 2014

The For-If Anti-Pattern

This isn't anything new in terms of coding advice (you can find stuff on the Internet about it everywhere), but I just caught myself using the for-if anti-pattern. The term anti-pattern refers to a coding style (a pattern) that is suboptimal or flawed in some way. For-if is an inefficiency that fails to leverage the given lookup or access mechanism and instead enumerates every single entry in a collection, checks to see whether it has the right ID, and then does something with it. In obvious terms:

For n = 0 to 300
 If n = CInt(userChoice) Then
  Console.WriteLine(messageTable(userChoice))
 End If
Next

It's obvious here; the above code could be:

Console.WriteLine(messageTable(userChoice))

And the message table is accessed directly. I noticed that I had been doing this with the Properties collection of DirectoryEntry:

For Each p as PropertyValueCollection In GetCurDir.Properties
 If p.PropertyName = Arguments(1) Then
  val = p(0)
 End If
Next

It hit me that I could have simply written:

val = GetCurDir.Properties(Arguments(1)).Value(0)

Moral of the story: check to see whether your collection supports direct accessing. You should definitely not be looping through a Dictionary to find a pair with a certain key and extract the value from the KeyValuePair - get the value directly by passing the key to its default property!

No comments:

Post a Comment