Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

10
  • 2
    @pstatix Couldn’t you imagine having several instances of your configuration? For example adopting a multi-tenant tenant architecture where every tenant wound use another configuration. My main argument here is not to prescribe the way to manage your configuration, but to challenge making it a singleton. In other words, if you need one instance of your config, just create one instance. If it is a global, and there’s no better alternative, tant pis. The singleton enforces unicity, so it should be used only if unicity is vital. Commented May 4, 2020 at 21:29
  • 2
    @pstatix using a singleton instead of a global doesn’t make your design better: it’s clever but it just hides the dependency to a global state, and will make refactoring more difficult if one day you decide to break your config in smaller pieces and inject those where needed. In other words, if misused, the singleton transfers at class level (so to the general concept) a need which in reality about object instances (so a specific need). And this is not consistent with a sound separation of concerns. Unfortunately, singletons are often misused and hence their bad reputation. Commented May 4, 2020 at 21:37
  • 1
    @pstatix Usually the recommended way is to create the configuration object once in your "root" class and pass it around via constructors (see stackoverflow.com/questions/130794/what-is-dependency-injection). That way you can substitute it easily in any class for testing purposes. Commented May 5, 2020 at 10:11
  • 1
    @pstatix A singleton is a global. You get it through some global name Commented May 5, 2020 at 11:10
  • 1
    To make an object only once without a singleton one simply needs to create it once in a method that is called only once. Main usually works for this. Once created it can be passed where needed. A singleton's only advantage is that you can call it from methods that are called more than once. It adds no extra safety from bad programmers. Bad programmers will construct it twice in main and they'll write a singleton with the if commented out. Commented Jul 6, 2020 at 23:30