Thursday, January 30, 2025

Contains Bad Choices – The Daily WTF

Programming LanguageContains Bad Choices - The Daily WTF


Paul‘s co-worker needed to manage some data in a tree. To do that, they wrote this Java function:

private static boolean existsFather(ArrayList<Integer> fatherFolder, Integer fatherId) {
        for (Integer father : fatherFolder) {
                if (father.equals(fatherId))
                        return true;
        }
        return false;
}

I do not know what the integers in use represent here. I don’t think they’re actually representing “folders”, despite the variable names in the code. I certainly hope it’s not representing files and folders, because that implies they’re tossing around file handles in some C-brained approach (but badly, since it implies they’ve got an open handle for every object).

The core WTF, in my opinion, is this- the code clearly implies some sort of tree structure, the tree contains integers, but they’re not using any of the Java structures for handling trees, and implementing this slipshod approach. And even then, this code could be made more generic, as the general process works with any sane Java type.

But there’s also the obvious WTF: the java.util.Collection interface, which an ArrayList implements, already handles all of this in its contains method. This entire function could be replaced with fatherFolder.contains(fatherId).

Paul writes: “I guess the last developer didn’t know that every implementation of a java.util.Collection has a method called contains. At least they knew how to do a for-each.”.

[Advertisement]
Keep all your packages and Docker containers in one place, scan for vulnerabilities, and control who can access different feeds. ProGet installs in minutes and has a powerful free version with a lot of great features that you can upgrade when ready.Learn more.

Check out our other content

Check out other tags:

Most Popular Articles