This discussion is archived
14 Replies Latest reply: Sep 24, 2008 2:28 PM by jschellSomeoneStoleMyAlias RSS

Singleton vs. Static

807589 Newbie
Currently Being Moderated
I'm developing an application and I have read a number of articles on the use of a Singleton vs. a static class (a class with all static members).

From my perspective, it seems that it's best to use static classes when you have pure, stateless functions. Singletons should be used when the information being held represents the state of an object (a single object, but an object nonetheless).

I may be opening a can of worms here, but as I am developing an API for other developers to use, I am really trying to make sure I do this right because, once it's in place and in use, it won't be something that is easily changeable in the future.


Thanks for any help!
  • 1. Re: Singleton vs. Static
    807589 Newbie
    Currently Being Moderated
    I would broadly agree, except I would add that you should avoid Singletons as they make unit testing much harder.
    Figuring out how you intended to support unit tests should be on your list of things to do before you release your API.
  • 2. Re: Singleton vs. Static
    807589 Newbie
    Currently Being Moderated
    1. Singletons: I find it interesting that in [Wikster's Singleton Pattern Article|http://en.wikipedia.org/wiki/Singleton_pattern], the first four references are:

    Patterns I hate #1: Singleton
    Why singletons are evil
    Singletons considered stupid
    Use your singletons wisely

    2. Make something a static utility method only if it never needs to be mocked during testing. How else can you replace it for unit tests?
  • 3. Re: Singleton vs. Static
    807589 Newbie
    Currently Being Moderated
    BigDaddyLoveHandles wrote:
    1. Singletons: I find it interesting that in [Wikster's Singleton Pattern Article|http://en.wikipedia.org/wiki/Singleton_pattern], the first four references are:

    Patterns I hate #1: Singleton
    Why singletons are evil
    Singletons considered stupid
    Use your singletons wisely

    2. Make something a static utility method only if it never needs to be mocked during testing. How else can you replace it for unit tests?
    Yeah, I found point 1 interesting, too.

    I do have to agree with what many people said about Singletons - they're essentially globals and globals tend to be bad (I know I have experienced torture at the hands of globals). At the same time, my dev team and myself cannot come up with something that works WITHOUT using Singletons. Unfortunately, I know I could not explain the entirety of the project here.
  • 4. Re: Singleton vs. Static
    807589 Newbie
    Currently Being Moderated
    IMHO Utility classes are ok if used with care....
    However, a good example of the mess you can get with utility classes is the Math class.
    One might assume that there should be no need to change pow() or sin().
    But you have strict floating point and non-strict floating point so you end up with Math and StrictMath. But on Sun's JVM these do the same thing so Math, just calls the StrictMath with the same method. If they were different there would be no simple way to test one implmentation against the other.
  • 5. Re: Singleton vs. Static
    807589 Newbie
    Currently Being Moderated
    edit: I take 2 back:

    If a library defines a class with static utilities methods:
    public class X {}
    public class Y {}
    
    public class XUtilities {
        public static X someUtilityMethod(Y y) {
            ///...
            return null;
        }
    }
    The client code can still handle the static methods in a way that permits mocking. First define an interface:
    public interface XInterface {
        public X someUtilityMethod(Y y);
    }
    The define the implementations: the standard one and mock ones:
    public class XImpl implements XInterface {
        public X someUtilityMethod(Y y) {
            return XUtilities.someUtilityMethod(y);
        }
    }
    
    public class XMock implements XInterface {
        public X someUtilityMethod(Y y) {
            //...
            return null;
        }
    }
    Finally, the "client" can use DI:
    public class XClient {
        XInterface x;
    
        public XInterface getX() {
            return x;
        }
    
        public void setX(XInterface x) {
            this.x = x;
        }
    
        public void someMethod(Y y) {
            //...
            X result = getX().someUtilityMethod(y);
            //...
        }
    }
  • 6. Re: Singleton vs. Static
    807589 Newbie
    Currently Being Moderated
    BTW: You can often get away with just one Singleton. You can use this to get all other "singletons". For such a Singelton I would make just store values and references (i.e. it has no real code so it doesn't need to be mocked) and add a reset() method called in your unit tests to ensure you are back to a known state.
  • 7. Re: Singleton vs. Static
    807589 Newbie
    Currently Being Moderated
    JavaDevGuy wrote:
    I do have to agree with what many people said about Singletons - they're essentially globals and globals tend to be bad (I know I have experienced torture at the hands of globals). At the same time, my dev team and myself cannot come up with something that works WITHOUT using Singletons. Unfortunately, I know I could not explain the entirety of the project here.
    What about using a framework like Spring? You can configure a bean to be a "Singleton", so-called, so that successive calls to get the bean from the factory yield the same bean. But your code uses DI so it doesn't depend on the singleton pattern and is testable.
  • 8. Re: Singleton vs. Static
    807589 Newbie
    Currently Being Moderated
    BigDaddyLoveHandles wrote:
    1. Singletons: I find it interesting that in [Wikster's Singleton Pattern Article|http://en.wikipedia.org/wiki/Singleton_pattern], the first four references are:

    Patterns I hate #1: Singleton
    Why singletons are evil
    Singletons considered stupid
    Use your singletons wisely

    2. Make something a static utility method only if it never needs to be mocked during testing. How else can you replace it for unit tests?
    Hide the static utility methods behind an adapter. You'll have one thin layer of delegation that, while not unit-testable, is simple enough to trust to old-fashioned developer competence. Gets you out of a tight spot, but I don't recommend designing for that. This approach can also be used as a stepping-stone to migrate code away from dependence on static methods. You don't have to refactor everything all at once, which can be painful, or downright impossible
  • 9. Re: Singleton vs. Static
    807589 Newbie
    Currently Being Moderated
    georgemc wrote:
    >
    Hide the static utility methods behind an adapter. You'll have one thin layer of delegation that, while not unit-testable, is simple enough to trust to old-fashioned developer competence. Gets you out of a tight spot, but I don't recommend designing for that. This approach can also be used as a stepping-stone to migrate code away from dependence on static methods. You don't have to refactor everything all at once, which can be painful, or downright impossible
    This is reply #5, right?
  • 10. Re: Singleton vs. Static
    807589 Newbie
    Currently Being Moderated
    BigDaddyLoveHandles wrote:
    georgemc wrote:
    >
    Hide the static utility methods behind an adapter. You'll have one thin layer of delegation that, while not unit-testable, is simple enough to trust to old-fashioned developer competence. Gets you out of a tight spot, but I don't recommend designing for that. This approach can also be used as a stepping-stone to migrate code away from dependence on static methods. You don't have to refactor everything all at once, which can be painful, or downright impossible
    This is reply #5, right?
    It is! I must've had a backwards premonition or something. That's what I get for answering a post without reading the rest of the thread, like a big eejit
  • 11. Re: Singleton vs. Static
    jschellSomeoneStoleMyAlias Expert
    Currently Being Moderated
    JavaDevGuy wrote:
    I'm developing an application and I have read a number of articles on the use of a Singleton vs. a static class (a class with all static members).
    Seems like a way to compare apples and oranges.
    From my perspective, it seems that it's best to use static classes when you have pure, stateless functions. Singletons should be used when the information being held represents the state of an object (a single object, but an object nonetheless).
    First we start by recognizing that singleton is a conceptual entity which represents an object. Objects have behavior and state.

    Then we look at implementing a singleton. One can implement a singleton using the standard pattern (from GoF) or one can use an entirely static front end. That is an implementation detail which does not change anything about whether it is singleton or not (although it can, very rarely, limit desired functionality.)

    Conversely one might also use a static class as a collection of related behaviors. Behaviors with no data are not objects. Thus, for example, java.lang.Math. That is not and never can be deemed a singleton.
    I may be opening a can of worms here, but as I am developing an API for other developers to use, I am really trying to make sure I do this right because, once it's in place and in use, it won't be something that is easily changeable in the future.
    Are you delivering a library or is this just part of of a another deliverable?

    The distinction is important. The Java API is a library which is delivered independent of the applications that use it. It has its own delivery schedule and a complete set of independent unit tests (with absolutely no dependency on applications).

    Conversely for an application that uses a database layer the database layer is not a library. It might be referred to that but its existence is tied to the application. It is delivered with the application and its schedule is always tied to it. And unit tests might exist that test functionality that either is known or discovered about the application rather than specifically about the layer.

    Deciding on the difference between the two impacts the design and architecture perspective that one must take.
  • 12. Re: Singleton vs. Static
    807589 Newbie
    Currently Being Moderated
    BigDaddyLoveHandles wrote:
    JavaDevGuy wrote:
    I do have to agree with what many people said about Singletons - they're essentially globals and globals tend to be bad (I know I have experienced torture at the hands of globals). At the same time, my dev team and myself cannot come up with something that works WITHOUT using Singletons. Unfortunately, I know I could not explain the entirety of the project here.
    What about using a framework like Spring? You can configure a bean to be a "Singleton", so-called, so that successive calls to get the bean from the factory yield the same bean. But your code uses DI so it doesn't depend on the singleton pattern and is testable.
    IoC is one of those rare little paradigm shifts that actually did turn the world on it's head, isn't it? I'm a synesthete, and IoC has a nice fuzzy purple colour and a glassy texture that I've historically found most appetising in one form or another. For some reason, dependency injection is a bold orange lumpy affair that I typically find macho things to be.
  • 13. Re: Singleton vs. Static
    807589 Newbie
    Currently Being Moderated
    georgemc wrote:
    IoC is one of those rare little paradigm shifts that actually did turn the world on it's head, isn't it? I'm a synesthete,
    Do you guys get a Pride Parade to march in?
    and IoC has a nice fuzzy purple colour and a glassy texture that I've historically found most appetising in one form or another. For some reason, dependency injection is a bold orange lumpy affair that I typically find macho things to be.
    Hmm... both taste like Buffalo Chicken Wings to me.
  • 14. Re: Singleton vs. Static
    807589 Newbie
    Currently Being Moderated
    BigDaddyLoveHandles wrote:
    georgemc wrote:
    IoC is one of those rare little paradigm shifts that actually did turn the world on it's head, isn't it? I'm a synesthete,
    Do you guys get a Pride Parade to march in?
    Yeh, a big spiky blue one. Pride's like porridge, though