Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single instance with methods in java

Tags:

java

I am wondering about programming decision - which I think is matter of style. I need to have single instance of class which has only methods and no attributes. To obtain that in java I have two options:

  1. create an abstract class with static methods within, thus it will not be possible to create any instance of the class and that is fine,
  2. use a singleton pattern with public methods.

I tend to go for second approach although met with 1. Which and why is better of those, or there is third option.

like image 857
Gadolin Avatar asked May 12 '26 20:05

Gadolin


1 Answers

Would it make sense for that singleton to implement an interface, allowing you to mock out those methods for test purposes?

I know it goes against testing dogma these days, but in certain situations I think a static method is fine. If it's the kind of behaviour which you're never going to want to fake for test purposes, and which is never going to be polymorphic with other implementations, I don't see much point in making a singleton. (Singletons are also generally the enemy of testability, although if you only directly refer to them in the injection part of your code, they can implement appropriate interfaces so their singletoneity never becomes a problem.)

It's worth mentioning that C# has "static classes" for this kind of situation - not only do they prohibit other code from deriving from or instantiating the class, but you can't even use it as a parameter. Basically it signals the intent very clearly.

I would definitely suggest at least having a private constructor to prevent instantiation by the outside world.

like image 57
Jon Skeet Avatar answered May 15 '26 10:05

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!