Singletons should be Humble

The Singleton pattern is one of the simplest in the Gang of Four book. This does have it’s place in code. It introduces some complications for testing.

I have recently started working on some Groovy code that uses the @Singleton attribute. This is a Groovy construct that turns any class into a Singleton. Groovy has the ability to alter the Abstract Syntax Tree between parsing and compilation.

This makes the code hard to test as the annotated class now has two responsibilities, it’s function and being a Singleton.

The easy way to split this is to use the Humble object pattern. Move the responsibility into a distinct class and use the Singleton as a gatekeeper.

Singletons work best if supplied by architecture not directly in a component. They are fine if Stateless but not otherwise.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s