CodeSOD: A Tern in the Stream

Java's streams feature allows developers to use functional programming techniques to operate on sets of data. Used correctly, it can create expressive and readable code. Used incorrectly, well…

Gevatter Tod found this while searching for a bug.

for (Entity media : e1, Entity e2) -> 0 - ((e1.getValue("Sortorder") != null ? (Integer) e1.getValue("Sortorder") : new Integer(0))) .compareTo((e2.getValue("Sortorder") != null ? (Integer) e2.getValue("Sortorder") : new Integer(0)))) .collect(Collectors.toList())) { .... }

Now, I don't know what the body of the loop is, but it's worth pointing out that the whole idea of using streams is that you can do all your operations in the streams pipeline, so mixing a for loop with a stream operation is suspicious. Especially when the result of the stream operation is to collect it back into a list: this starts a stream, sorts the stream, and collects the results into a list. Then we iterate across the list.

The real ugly in this, though, isn't the misuse of streams, but the way we sort. Ternaries to handle nulls, wrapped in parentheses so that we can treat the results as objects. Bonus points for hard coded constants being repeated, which isn't a WTF but does annoy me.

Gevatter Tod has this to say:

This is exactly what I found while searching for a bug in our CodeBase.
I didn't change anything. Not even the formatting. So you can enjoy it in all of it's beauty.

[Advertisement] Keep the plebs out of prod. Restrict NuGet feed privileges with ProGet. Learn more.

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published.