aspose file tools*
The moose likes Java in General and the fly likes Singleton versus Static class? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Singleton versus Static class?" Watch "Singleton versus Static class?" New topic
Author

Singleton versus Static class?

Avianu Sud
Ranch Hand

Joined: Jan 20, 2002
Posts: 55
When would I use a Singleton? versus just making the methods static?

Are there any advantages of the 2 options? or just stylistic differences?

Thanks in Advance,
- Avi
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
They are both very poor (albeit common) design decisions. Define your behaviour on an interface before worrying about the implementation. After all, you have to know "what to do" before you figure out "how to do it".


Tony Morris
Java Q&A (FAQ, Trivia)
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
Always make your methods static unless you can't. In other words you need access to the object's state. I highly recommend Effective Java. It covers topics such as defaulting to static methods, using singletons, and why both are considered excellent design principles.

http://java.sun.com/docs/books/effective/

As far as your singleton versus static, they have nothing in common. Singleton's simplify maintenance of shared state. However, you may have to serialize access so it can cause performance problems. Static methods have no such scalability issues and they provide no facilities for sharing state. Not much of anything in common with singleton.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Another way of saying what Tony said is to choose Singleton over all static methods, but to keep your options open -- i.e., use an interface to represent the methods, and don't write the application assuming there is only one instance of the class. The fact that there's only one should be a closely guarded secret so that if someday, in fact, things change and there are two, or ten instances, very little code needs to change.


[Jess in Action][AskingGoodQuestions]
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by Rick O'Shay:
Static methods have no such scalability issues and they provide no facilities for sharing state. Not much of anything in common with singleton.


That's somewhat disingenuous. The two alternatives under discussion are first, a single object with state in its instance variables, and second, a bunch of static methods and state in the class's static variables. Doesn't matter whether the second sounds odious -- that's what the newbie designer will think of first. A bunch of static methods sharing some static data is a natural projection of their tried-and-true procedural programming experience onto Java. And the proper recomendation is to go for the single object, but emphasize the "object" and go easy on the "single."
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
That's true. You could use class fields as singleton state so in that regard they are alternative solutions to a single problem.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
I do not condone the use of the singleton antipattern in any way, shape or form. Don't they teach you that global variables are nasty at school anymore?

<edit>
I should also point out that googling "singleton antipattern" shows some inclination to suggest that developers are starting to wake up to the fact.
</edit>
[ August 28, 2005: Message edited by: Tony Morris ]
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
>> I do not condone the use of the singleton antipattern in any way, shape or form.

Which means nothing.

>> Don't they teach you that global variables are nasty at school anymore?

Ah, a veiled point. You believe singletons are global variables, which explains your confusion. Let me help: singleton does not imply a global variable. The astute programmer will hide the singleton behind a factory method that lazy creates the singleton on first access and hands back the same object. Subsequent calls get the same object.

BTW, having a few global variables in a central place is a convenience with few harmful effects if used correctly, but singleton does not require their use.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
It does mean something, since it was implied by an earlier comment that that is what I meant, and I would never imply such a thing, hence correction is in order.

How your explanation somehow invalidates the assertion that a singleton implies a global point of access is up for grabs. Singletons exist exclusively for that very single reason i.e. you wish to make a change on an object and have those changes reflected globally - for the case of a singleton, "globally" typically means throughout the system classloader. Passing a callback is always preferred and is often more intuitive (though not always immediately). I take it you didn't google.
Ronnie Ho
Ranch Hand

Joined: Aug 10, 2005
Posts: 47
If I am building a web based application, I'll load up all the objects from the database during startup and those objects stay in memory forever as singleton objects. Whenever I do modifications, I'll update those objects as well as the database. I do that to avoid query the database every time if the request doesn't require modifications to the objects. Do you guys think it's a bad design? Or what's a better solution? Thanks.
Lasse Koskela
author
Sheriff

Joined: Jan 23, 2002
Posts: 11962
    
    5
Originally posted by Ronnie Ho:
If I am building a web based application, I'll load up all the objects from the database during startup and those objects stay in memory forever as singleton objects. Whenever I do modifications, I'll update those objects as well as the database. I do that to avoid query the database every time if the request doesn't require modifications to the objects. Do you guys think it's a bad design? Or what's a better solution? Thanks.

Without knowing the full context of your particular application, here are some questions that you might want to ask yourself about your design:
  • Do I really need the performance boost enough to overcome the added complexity of a custom caching implementation?
  • Could I use a pre-existing caching implementation instead of building (and maintaining/bugfixing) my own?
  • Do other applications need to be able to update the state of those objects in the database behind your back? If they do, how are you handling cache expiration etc.?


  • Author of Test Driven (2007) and Effective Unit Testing (2013) [Blog] [HowToAskQuestionsOnJavaRanch]
    Ronnie Ho
    Ranch Hand

    Joined: Aug 10, 2005
    Posts: 47
    Thanks for your reply.

    Could I use a pre-existing caching implementation instead of building (and maintaining/bugfixing) my own?



    Can you give me an example of a pre-existing caching implementation that's available? Thanks.
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    Originally posted by Ronnie Ho:
    If I am building a web based application, I'll load up all the objects from the database during startup and those objects stay in memory forever as singleton objects. Whenever I do modifications, I'll update those objects as well as the database. I do that to avoid query the database every time if the request doesn't require modifications to the objects. Do you guys think it's a bad design? Or what's a better solution? Thanks.


    An option that is always available is to do away with the global access point and pass the one object around instead. That way, only one single class, the one creating the instance, needs to know that there is exactly one. All other objects aren't coupled to the fact that there is only one instance.

    Google for "Just Create One" for an excellent article by Robert C. Martin on that topic.


    The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    Originally posted by Rick O'Shay:
    Always make your methods static unless you can't. In other words you need access to the object's state.


    Access to the object's state isn't the only motivation for using instance methods - polymorphism is another one, and a very strong one. Using static methods makes your code much less flexible.
    Stan James
    (instanceof Sidekick)
    Ranch Hand

    Joined: Jan 29, 2003
    Posts: 8791
    Amen! Static methods are very strong coupling. You specify an exact class all over your code. For example, in a lazy moment when I was first learning Java I put this all over my code at home:

    Logger.log( "message" );

    Now if I wanted some of my projects to use one logger and other projects to use another one, I'd be in a bad place, maybe have to change Logger to NewLogger in a whole lot of classes. If I'd coded:

    private Logger logger = Logger.getLogger();
    ...
    logger.log("message");

    I could change getInstance() to read configuration or choose by the day of the week or whatever logic I need to return any implementation of an interface, say ILogger. The concrete logger might be a singleton or not. Nobody ever needs to know.

    Static seems to save a few keystrokes, but is highly coupled and hard to change!
    [ August 29, 2005: Message edited by: Stan James ]

    A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
    Pradeep bhatt
    Ranch Hand

    Joined: Feb 27, 2002
    Posts: 8919

    I need to implement a set of utility methods which do not have any state. What is better approach - A class with a set of static methods or a singelton.


    Groovy
    Stan James
    (instanceof Sidekick)
    Ranch Hand

    Joined: Jan 29, 2003
    Posts: 8791
    Static methods are quick & dirty and attractive to lazy typists (like me) but they are very rigid and hard to replace over time. Using static methods is a bet that this utility will be stable and universal until the end of time. It could happen.

    Once you've gone beyond static methods singleton or not doesn't matter all that much. Still, one of the signatures of a singleton is a factory method, and that's a good idea. You wind up like this:

    UtilityInterface utility = UtilityFactory.getInstance();
    utility.someMethod();

    You can put the first line in your instance variable declarations so the rest of the code is no bulkier than it would be with static methods. But now if somebody needs to make a new implementation of UtilityInterface they can plug it into the factory and no other code changes.
    Ram kovis
    Ranch Hand

    Joined: Jun 23, 2005
    Posts: 130
    Originally posted by Pradip Bhat:
    I need to implement a set of utility methods which do not have any state. What is better approach - A class with a set of static methods or a singelton.


    Pradip,

    I raised the same question here about Singleton for util class
    I always worry about using singleton.. If we have to take care off multi-threading etc, why to go for singelton.. simplly, create a new object and proceed.. :-))
    Never really understood the purpose of singleton :-))
    Ram kovis
    Ranch Hand

    Joined: Jun 23, 2005
    Posts: 130
    Also,

    can somebody give me some examples where do you use singleton in real time applicaitrons..

    Thanks
    Vinod John
    Ranch Hand

    Joined: Jun 23, 2003
    Posts: 162
    From Unit testing perspective, static methods are ok if they are "self contained", i.e, they don't call any downstream operations other than methods for the "standard utility library". But if these methods calls some downstream business operation(s) then, Unit testing the code that calls this static method might be dirty, unless or until there is a way to mock static methods ... is there one ?
     
    Don't get me started about those stupid light bulbs.
     
    subject: Singleton versus Static class?