• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Singleton versus Static class?

 
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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".
 
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ernest Friedman-Hill
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 531
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 531
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
>> 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
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
author
Posts: 11962
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.?

  •  
    Ronnie Ho
    Ranch Hand
    Posts: 47
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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.
     
    author
    Posts: 14112
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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.
     
    Ilja Preuss
    author
    Posts: 14112
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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.
     
    (instanceof Sidekick)
    Posts: 8791
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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 ]
     
    Ranch Hand
    Posts: 8946
    Firefox Browser Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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.
     
    Stan James
    (instanceof Sidekick)
    Posts: 8791
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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.
     
    Ranch Hand
    Posts: 130
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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
    Posts: 130
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Also,

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

    Thanks
     
    Ranch Hand
    Posts: 162
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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 ?
     
    reply
      Bookmark Topic Watch Topic
    • New Topic