Anti-for-if programming pattern

Over the years, I’ve seen tons of anti-programming patterns. I feel like I should share something with you all.

Today, I’m going to introduce an anti-pattern that I call the anti-for-if programming pattern”If you’re interested, check out this article: Why are for loops hateful? “Seats, but all you need is an edge.”

This is a special anti-for-case pattern, where only one of all cases will be null.

for (int i = 0; i < 100; i++) {
  if (i == 42) { do_something(i); }
}

This case can be simply written as

foreach (string filename in Directory.GetFiles("."))
{
    if (filename.Equals("desktop.ini", StringComparison.OrdinalIgnoreCase))
    {
        return new StreamReader(filename);
    }
}

This anti-for-if pattern can take various forms. for example:

if (File.Exists("desktop.ini"))
{
    return new StreamReader("desktop.ini");
}

It traverses a directory to find a specified file, and if found, returns the data stream of the file. A less frustrating way to write this code is

foreach (object o in hashtable.Keys)
{
    if (o == "target") return hashtable["target"];
}

Note that both versions of the code snippet have the same race condition: if the desktop.ini existed but was deleted before you created the StreamReader, you would get a FileNotFoundException.

Another example:

foreach (object o in hashtable.Keys)
{
    if (o == "target") return hashtable["target"];
}

Equivalent to

return hashtable["target"];

I’m guessing these guys don’t like looking for a book by title in the library, because their approach is so cumbersome:

They came to the librarian and said, “Give me all your books,” and then they took a basket full of thousands of books and sat in the corner and said to themselves:

“No, the title of this book is wrong”,

“No, this one isn’t either”,

“The title is still wrong.”

“What about this book?”

“No, not this one.”

“God, when do I want to flip through books like this…”

Leave a Comment

Your email address will not be published. Required fields are marked *