Search code examples
c#asp.netdesign-patternssingletonfacade

Trying to figure out if this code creates any benefit by using a Singleton


I'm working on a project where one of the co-developers (and previous developers) use a Singleton/Facade for just about every page of class that has a lot of method calls inside of it, but that don't actually maintain the data.

For instance:

public class FooFacade
{
    private static FooFacade m_facade = null;
    private static DataAccessManager m_dataAccessMgr = null;

    public StringBuilder Status {get; set; }

    private FooFacade()
    {
        this.Status = new StringBuilder();
    }

    public static FooFacade getInstance()
    {
        if (m_facade == null)
        {
            m_dataAccessMgr = DataAccessManager.getInstance();
            m_facade = new FooFacade();
        }

        return m_facade;
    }

    public void clearStatus()
    {
        this.Status.Remove(0, Status.Length);
    }

 public void Method1(string value1, int value2)
    {
     // DO SOMETHING
    }


 public List<string> Method2(string value1, int value2)
    {
     // DO SOMETHING ELSE
     // RETURN LIST
    }

Now, I have certain issues with the naming convention and the fact that they have the Singelton inside the same class as the Facade and the fact that the Facade isn't really a Facade. (but that's a whole different conversation).

So my question is whether there really is a benefit from this. The best that the developer could explain is that it is better for memory management since you're not constantly creating and disposing of objects.

Our application is not an enterprise level app and we don't have issues with memory. Anytime the site is slow, it's really due to the database and not the code.

Thanks for your help. I'm a developer who loves to know why to make myself a better developer. Since I can't get it from the developer in words that make sense, I'm reaching out to you guys.

Thanks, Chad

UPDATED Thanks to the comments below, I know that the status is a serious concern as it has a chance of being a huge security flaw. Is there any benefit to using this code in a Singleton when it comes to memory management, speed, etc? Or would it just be easier to instantiate FooFacade every time I need it.


Solution

  • Because your object has an internal state (Status) you are asking for trouble. Specifically, if ever the singleton is used from within multiple threads (for example in a web app) the code will probably just won't work.

    Use singletons only if you have classes that have no internal state.