4

I am relatively new to programming (1yr field experience now) and I think that I am overusing the singleton pattern and I need some input on how to do it in a better way. Right now I am using singletons as an excuse for static global data. I use singleton for Application Status, Application Settings and also a lot for "Managers". Basically they are all objects which are needed by different parts of my application. I think this pattern makes it easier then creating one object and inject it into all parts that need this.

Any downsides to this approach? Any suggestion regarding this matter?

Md Mahbubur Rahman
  • 4,747
  • 5
  • 32
  • 38
metacircle
  • 171
  • 5

2 Answers2

1

Sounds like a typical case of Singleton abuse. It's really easy to not think about separating responsibilities properly, it's much easier to just stick everything to global data. This is exactly why Singleton has bad reputation, it allows giving a cool name to bad practices.

It is hard to give any exact advice without knowing more about your application. You mention Application Status and Settings. From my experience these are usually a mixed bag of miscellaneous data that are not related to each other. If this is the case, then injecting the big Status/etc. class to every other class isn't much of an improvement compared to Singleton. What you need to do is break up the big class. Depending how large your code base is, this can be really difficult, because global data can cause everything to be dependent of everything.

simoraman
  • 2,318
  • 17
  • 17
0

In implementing the logic for a singleton, you're going to make it harder to test your application with different values.

I suggest you look at creating a single instance of your settings class but rather than make it globally accessible, you use dependency injection to provide a reference to each of your classes.

In terms of global status, this again could be used with DI as per my suggestion above however I would suggest that application status does not need to be global. I would reexamine your design and try and decouple the need for classes to know about global state. What I feel would be a better alternative is for you to have Factories where necessary that are injected with your settings and construct your objects for you.

Sam
  • 6,152
  • 2
  • 20
  • 34