CodeSOD: All the Single Objects

I have a bit of a vendetta against the Singleton pattern. It's not to say that I won't use it, it's just that it's a pattern that gets overused and misapplied. The result is, instead of guaranteeing that instance of an object exists (because there can be only one), and just create broad globals.

Today, George sends us some code that is in a Java factory class that constructs thread pools. In this case, the thread pool itself is returned as a singleton. I've got some questions about the logic of why that's the case, but that's what it is.

And then there's this method/comment combination which is just… perfect.

/** * @return Returns true always. */ public boolean isSingleton() { return false; }

That's the funniest part of the object, by far, and the part George wanted to draw to our attention. I will add, though, that it has a unique calling convention. You see, if you just call getObject or the factory, it throws an exception. To properly construct the factory to return its singleton you must do something like this:

ThreadPoolExecutorFactoryBean tpb = new ThreadPoolExecutorFactoryBean(); tpb.setCorePoolSize(10); tpb.setKeepAliveTime(5); //a dozen more of these tpb.afterPropertiesSet(); pool = tpb.getObject();

It's like the worst possible attempt at creating a fluent API (each of the setter methods returns void). Plus, there's no way for other callers to detect if the object is initialized.

And of course, it changes our interpretation of the isSingleton method- because this very much isn't a singleton. So the method is correct, the comment is wrong, and everything about this should be thrown in the wood chipper and used to fertilize a pumpkin patch.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published.