-3

what is the better approach?

Let us assume a scenario in which there is a utility class that is used by other classes. What is better to use in this case, a singleton class which can be instantiated exactly once or should i make all the fieds static?

user3753682
  • 187
  • 4
  • 13
  • 3
    That depends on what the fields are and how they are used. – azurefrog Aug 30 '16 at 15:37
  • Is 'neither' a valid answer? – bradimus Aug 30 '16 at 15:38
  • Actually, the OOP principles state that there should be no "utility" classes, since they're purely procedural. So I'd advice you to try to rethink your current architecture. Though if you *really* need some utility methods, then of course `static` methods would be better. Singleton itself is also a class with some state and behavior, while utility methods assume no state. – Scadge Aug 30 '16 at 15:43
  • Neither is a very valid answer. Singleton should be voted off the GoF island. – duffymo Aug 30 '16 at 16:02

1 Answers1

0

In object-oriented programming generally you should avoid singletons and utility classes if possible.

However, if really needed I'd go with utility class without any fields - just static methods. By definition utilities should be rather set of stateless functions. Such are well testable in comparison to untestable singleton (which is done with static field). If you need to keep the state then go towards true objects.

As stated in the comment, you can have a safe singleton done by dependency injection, without static state.

Michal Kordas
  • 10,475
  • 7
  • 58
  • 103
  • 1
    Singleton is very testable if done correctly - i.e. through DI. It's the `static` references to the singleton that cause issues - same as the `static` methods; no way to mock them. – Boris the Spider Aug 30 '16 at 15:41
  • @BoristheSpider I've stated that I mean static mutable fields :) – Michal Kordas Aug 30 '16 at 16:30
  • I suppose what you actually mean is "_do not implement your singleton in a non threadsafe manner as it won't be threadsafe_" - this is obviously a tautology and not in any way helpful. `static` mutable fields can be perfectly thread safe if they're `volatile` or access is `synchronized` or any number of other options for making them threadsafe. – Boris the Spider Aug 30 '16 at 16:32
  • @BoristheSpider right, I've edited the answer a bit, can you please check? – Michal Kordas Aug 30 '16 at 16:54