Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Singleton is a common pattern implemented in both native libraries of .NET and Java. You will see it as such:

C#: MyClass.Instance

Java: MyClass.getInstance()

The question is: when writing APIs, is it better to expose the singleton through a property or getter, or should I hide it as much as possible?

Here are the alternatives for illustrative purposes:

Exposed(C#):

private static MyClass instance;
public static MyClass Instance
{
    get {
        if (instance == null)
            instance = new MyClass();
        return instance;
    }
}

public void PerformOperation() { ... }

Hidden (C#):

private static MyClass instance;

public static void PerformOperation()
{
    if (instance == null)
    {
        instance = new MyClass();
    }
    ...
}

EDIT: There seems to be a number of detractors of the Singleton design. Great! Please tell me why and what is the better alternative. Here is my scenario:

My whole application utilises one logger (log4net/log4j). Whenever, the program has something to log, it utilises the Logger class (e.g. Logger.Instance.Warn(...) or Logger.Instance.Error(...) etc. Should I use Logger.Warn(...) or Logger.Warn(...) instead?

If you have an alternative to singletons that addresses my concern, then please write an answer for it. Thank you :)

share|improve this question
2  
The "hidden" variant reminds me of sites.google.com/site/steveyegge2/singleton-considered-stupid –  delnan Jul 1 '13 at 12:07
5  
I have an even better suggestion: Avoid Singletons –  Uooo Jul 1 '13 at 12:21
    
@delnan I'm reading through the post. Informative so far. @w4rumy I am not a big fan of "never use..." or "never do...". There is a time and place for everything (as long as it's OOP). In my application, I have a log4net/log4j logger. I've created a class called Logger, and had been wondering whether to provide Logger.Error("") or Logger.Instance.Error(...) functionality. The native libraries all use Instance (e.g. AppDomain), but I feel that it's a bit superfluous. –  Sinker Jul 1 '13 at 12:34
1  
@sinker - it is, and restricting all of your modules to a common insance is a terrible idea. Modules very often want different implementations. Requirements very often shift to need variations in the modules (we want to now log things to the network except for network errors). Tests very often want different instances. Concurrency becomes complex with shared instances. Reuse becomes neigh-impossible. And on and on. Just do a search, I've commented here personally a ton about it. Singleton anti-pattern should provide even better arguments. –  Telastyn Jul 1 '13 at 14:37
1  
Best practice for using it, if your have to: csharpindepth.com/Articles/General/Singleton.aspx –  Jesse C. Slicer Jul 1 '13 at 14:58

2 Answers 2

up vote 9 down vote accepted

I think hiding Singleton is a bad idea. If you don't have a way to get a reference to the created instance via a getInstance() method, how you are going to do it considering that Singleton classes do not have public constructors? There is no way to get that reference. That means that if you decide to "hide" the Signbleton, your only option is to check in every public static method of the Signletone class whether the instance was already instantiated and if not, do it. So your code becomes something like this:

class BadSingletone {
    private static MyClass instance;

    public static void PerformOperation()
    {
        if (instance == null) { instance = new MyClass(); }
        ...
    }

        public static void PerformSomeOtherOperation()
    {
        if (instance == null) { instance = new MyClass(); }
        ...
    }

    public static void PerformYetAnotherOperation()
    {
        if (instance == null) { instance = new MyClass(); }
        ...
    }
}

littered with all those instantiation checks. You can of course encapsulate the check in a separate function but you will again have to call it in every public static function of the class. And what if you accidentially forget to include it in one of the functions? Users of the class will not be too happy about it.

So, to my mind, hiding Singleton does not make sense - it makes you litter your code with unneccessary checks.

share|improve this answer
    
Nice answer. I don't have enough reputation to vote-up :( –  Sinker Jul 1 '13 at 12:25
    
@Sinker that you for the assesment of my little efforts. You can still show your appreciation by formally accepting it :) –  akhilless Jul 1 '13 at 12:31
    
I'll give people the chance to answer too :) –  Sinker Jul 1 '13 at 12:34
    
:) fair enough. –  akhilless Jul 1 '13 at 12:38
1  
Playing devil's advocate: Couldn't one create a private static property or method which takes care of this, much like when the instance isn't hidden? –  delnan Jul 1 '13 at 12:50

Technically, I don't believe it's still considered a singleton pattern unless you expose the instance to other classes. It's just a private static member. That being said, in general the smaller the scope of a variable, the better. If other classes don't need it, don't share it. However, in most cases it's going to be much simpler just to instantiate the static member at declaration instead of checking everywhere if it's already been instantiated.

share|improve this answer
    
I guess what you're saying is the test is whether the other objects need to work with the instance directly, right? –  Sinker Jul 1 '13 at 14:26
    
That's right. Most oriented design principles are easier to differentiate by looking at the calling code. –  Karl Bielefeldt Jul 1 '13 at 14:32
    
Well if both Sun and Microsoft use that design, I guess it's worth considering! I never considered why that might be the case, but your point goes some way to explain the mentality. –  Sinker Jul 1 '13 at 14:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.