I know there has been 1 million and 1 discussions about Singletons on SO and here and I have had to clean up my fair share of terrible singletons in our code base; one of the reasons I am gun-shy here. But I am running into a situation where I feel like a Singleton is a reasonable solution and wanted to see what others think.
Quick setup: we have a set of interfaces which extend the Java functional interfaces of Consumer, Function, etc. to make the semantics cleaner mostly. One of these is as follows. JaxbClass is a POJO from the Jaxb generated XML bindings and KbType is an Enum used load data down. Pretty much a way of wrapping the binding classes with logic.
public interface KbTypeMapper extends Function<T extends JaxbClass, KbType>{}
Most classes which implement this interface do keep track of some internal state and so being able to have multiple instances of these classes is required, but for the current class I am implementing there is no internal state so there is no reason to ever instantiate more than one object of this class.
Objects which implement this interface are usually injected as dependencies and I would not change this for this one class. The param signature for most places this injection happens is something along the lines of Function<T,KbType>
. I would just replace instances like this:
SomeClass x = new SomeClass(new SpecificKbTypeMapper())
With:
SomeClass x = new SomeClass(SpecificKbTypeMapper.instance())
I could turn this into a static utility type class and just inject StaticUtilility::functionName
but then that would not fit with the overall design and would not actually implement our own interface which I think would be confusing.
I don't see a problem testing the class itself nor mocking the class since the single instance is still being injected where it is actually used.
Am I completely wrong in that a singleton is a perfectly fine solution here? Or am I just over engineering and should just keep a bunch of new object instantiations?