Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum-style singleton vs static instance getter

Tags:

java

singleton

I got used to writing enum-style singleton when all of a sudden, someone reviewing my code asked me change it because it is not in the project's coding convention. He asked me what is the benefit, I just said it is easier to write.

I just want to know if there's really no benefit in using it. I understand that enum for java might not have been implemented for this purpose but even then, is it wrong to use it this way?

like image 506
demotics2002 Avatar asked Jan 21 '23 02:01

demotics2002


1 Answers

I got used to writing enum-style singleton when all of a sudden, someone reviewing my code asked me change it because it is not in the project's coding convention. He asked me what is the benefit, I just said it is easier to write.

Another benefit of enums-style singletons over classic ones is that they have singleton semantics in the face of Java Object Serialization. (The Java Object Serialization and the enum base-class combine to ensure that deserialization doesn't create copies of enum constants. It is rather hard to get this right for a singleton implemented the classic way. And if you get it wrong there can be multiple instances of some singleton class ... and potentially problems.)

But I'd be inclined to carefully examine the basis for your colleague's objection.

  • Does the coding style specifically forbid enum's ?
  • Does the coding style specifically forbid enum-style singletons ?
  • Does the coding style specifically prescribe a particular way of implementing singletons ?

If none of the above, then "not in the coding standard" doesn't sound like a valid objection. (Surely, something doesn't need to be explicitly "in" the coding standard to be allowed ... that would be control-freak crazy stuff!)

My guess is that your colleague has spotted an example of a singleton in your coding standard, and concluded (incorrectly) that it means that singletons must be implemented that way.

(Or maybe you really are lumbered with an overly prescriptive coding standard. If that's the case, you have my sympathy.)


The other point is that the Singleton pattern needs to be used sparingly, as it is an impediment to testability, and potentially problematic for applications that are deployed in web containers and the like.

like image 76
Stephen C Avatar answered Feb 01 '23 16:02

Stephen C