Is it bad to use Singletons for immutable no-argument classes?

SebasH :

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?

Dmitry P. :

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:

  • An application constructs one object instead of many; Keep in mind that generally constructing a new object is a cheap operation in Java. If your objects do not live long, GC will collect them without significant impact on the performance of your app. This is applicable if you don't have to create thousands of such objects per second.

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=82411&siteId=1