jeudi 9 février 2017

Singletons - Is this bad code? [on hold]

I've consistently heard that singletons are generally bad, and most people would look at the below and suggest it should be implemented differently:

ChatManager.Instance.WriteMessage("Hello world");

But what if ChatManager is implemented as:

public class ChatManager
{
  // some methods

  public static ChatManager Instance { get { return DependencyResolver.Resolve<ChatManager>(); } }
}

Based on everything I've heard - basically that singletons should be replaced with dependency injection for most (stateful) objects - this is now okay, but I have some trouble seeing how it's functionally different from the more traditional singleton approach.

Looking at one of the more popular SO questions on this matter, the accepted answer lists 4 reasons why singletons are bad, of which 2 (#2, #3) are definitely solved using the above. #4 listed is true regardless of whether the dependency is passed in through a constructor, as is often the case for ASP.NET controllers, or resolved via your chosen dependency manager.

So, is this considered bad form, or good software engineering practice?

Aucun commentaire:

Enregistrer un commentaire