views:

145

answers:

4

The 'singleton-ness' of a class is an important aspect of how a class should be used. However, it usually doesn't have any explicit status in the exposed API of a class. Yes, conventional method names such as getInstance() are often used, but that's not exactly what I'm referring to here.

A 'tag interface' is an interface which contains no methods or data. An example of a tag interface is Serializable.

Would it not be useful to define a tag interface for singletons? This would:

  • allow them to be easily identified in the code base of a project
  • be more explicit
  • provide a place to document how singletons should be treated. As one example, one could mention that long-lived objects are fruitful sources of memory leaks, and that singletons should never be wired to short-lived objects.

This is a simple idea, but I have never seen it mentioned anywhere.

+1  A: 

It's an interesting idea, but I'm not sure how useful it is. Your third bullet point is a nice point.

The better argument might be "Why Singletons?" You'll certainly be making life easier for the Google Singleton Detector to find them and identify them for extermination. Their FAQ can express my view at length.

duffymo
A: 

Why not use a DI/IoC Container and let it manage the lifetime of your objects? As you say, the lifetime of a class does not need to be reflected in its public interface.

TrueWill
+1  A: 

You've stepped into a religious war here, but to me it seems that your idea has merit. So long as there are Singletons, I think it would be good if the compiler and JVM could enforce their atomic singleness.

The problem is that Singletons have become controversial, because they're prone to abuse. People opposed to their use point to secret global state, hidden dependencies, and massive overuse.

None of these, of course, are actually inherent in the notion of Singleton-ness, but that doesn't change the controversy.

Your case here isn't helped by using Serializable, because as Tom points out, that's controversial in itself. Of course, the fact that Serializable is held to have been a mistake by some writers doesn't necessarily make it so. Personally, I don't use it, but not because I think it's a mistake per se... I just find there are better ways to persist and retrieve state that better match my users' needs.

There are, of course, other marker interfaces - Cloneable, EventThreadListener, and SingleThreadModel, if memory serves. You might get further if you used them as a model.

Incidentally, I think most writers are referring to what you call a "tag interface" as a "marker interface". Not a big deal, but it might help your search for other thoughts on the topic.

CPerkins
A: 

I agree with TrueWill above about using a DI framework to handle the objects life cycles. And using Guice will give you a Singleton annotation to tag the singtons. :)

mlk