CodeSOD: Unaccountable Counting

Ulvhamne sends us some bad code that, well, I think at this point we should really coin a name for this particular anti-pattern.

    @Override
    public int getNumOfItemsInDataContainer(int parDataId)
    {
        int numberOfItems = 0;
        for (Integer x : myTransactionDataContainerMap.keySet())
        {
                numberOfItems ++;
        }
        return numberOfItems;
    }

This C# function wants to get the number of items contained in a dictionary. To do that, it iterates across the set of keys, and increments a counter. This is instead of using the size field that's part of the dictionary container.

This one adds a lovely bonus of taking a parameter parDataId, and doing nothing with it.

Marking the parameter as par is an example of so-called "Apps Hungarian", where the prefix is meant to represent the "logical" datatype or purpose of the variable- semantic information, instead of type information. While marginally better than iDataId, I still hate it. Also, if your methods have so many local variables in scope that you need to distinguish them from the parameters somehow, lest you get confused, that's an even bigger code smell.

All the Hungarian nonsense aside, this is an example of the very common anti-pattern of manually counting the items in a container when the container already can report that information.

So what do we call that? "Container Countification"? "Fingers and Toes"? "Sesame Street Counting"?

[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!

This post originally appeared on The Daily WTF.

Leave a Reply

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