I am working on a small Java Project right now, and while doing so there where multiple classes created which represent some kind of Constant behaviour for example use as default return value for other methods.
Now what all these have in common is, that they are completely immutable and that they only have a no argument constructor. This means that creating multiple instances of that class will always result in identical objects.
Is it better to just create a new instance everytime these classes are used or is this a acceptable case to use the singelton pattern?
Let's consider pros and cons of singleton assuming you have a small project and immutable classes that are used as default return values.
Pros of singleton in this case:
Cons:
More code to read and write;
While writing getInstance()
methods might not look like a big deal, other people (potentially) working with you will spend some time exploring what getInstance()
really does when fixing bugs or just undertanding some business logic. I've seen a number of surprising getInstance()
methods though they had a conventional name.
Potential concurrency issues;
Even if your project is small you may want to utilize multiple threads. In this case you have to write getInstance()
as a synchronized method, introduce double-checked locking, use enums or something else.
Even if you are aware of this peculiarity, it is not guaranteed that other developers won't make a mistake.
So there is no single right answer I think, it depends on how you see the evolution of your project in future.