Day 19: Avoid Singletons

Design patterns exist to solve common problems found on the development of object oriented software. As such, the singleton pattern exists to satisfy the need for code that is available to the whole application. It also helps when we want to enforce that only one instance of an object exists during the lifetime of the application.

The problem with the use of singletons is that the requirements above contradict a lot of the paradigms of object orientation. First of all, if some code is available to the whole application without creating objects, it can just be viewed as a structured piece of code, which could be easily implemented as a set of functions.

If one doesn’t need to create or destroy objects, then there is no need to use an object in the implementation, unless you’re using a language such as Java that has only objects.

As seen above, singletons don’t pass the ‘smell’ test of a pattern for the creation of solid code. Despite this, singletons were once a celebrated design pattern. A lot of singletons can be found everywhere in modern code. It is necessary, however, to be aware of some of the problems you will find when using them:

  • Singletons are hard to test: Since it is difficult to have any control about how the singleton is created, testing of a singleton in a controlled setting becomes very complicated. Sometimes, a singleton assumes a lot about the programming environment to work properly, and as a result it is not possible to create one of them in isolation.
  • Hard to reuse: for the same reason given above, singleton’s are hard to integrate to other code. They become non-reusable because they have to assume so much about the environment of any single program.
  • Allow indiscriminate use of resources: another big problem is hat there is no simple way to localize the use of a singleton. Once it is available, it can be used by the whole application, by definition. This has implications in the areas of safety, as well as in avoiding mistakes in the use of this shared resources.

Alternatives

Although singletons are in use in so many places, it is possible to avoid them in many occasions. Here are a few tactics that you can use to get rid of unnecessary singletons.

  • Convert into standard classes when possible: sometimes it is not so much work to convert a singleton into a traditional class. Just make sure that the initialization is done only when the first object is created. If there is a single resource that needs to be shared, for example, a network connection, you can use a static member variable to store that resource. In this way, you can have multiple objects that are still referring to a single resource.
  • Use static member functions in some cases: sometimes a singleton is improperly used when just a few static methods would work. This is a case when it is easy to remove the singleton, because there is no central resource that is shared. While static methods are not the best thing in the world, they at least are easier to test than a monolithic object.
  • Determine where the singleton is used. Sometimes it is applicable to just a small part of your app. When that happens, create a class that may used only by that part of the application. For example, if you using C# that might be a class visible only to the package. In this way, you avoid the indiscriminate access provided by singletons.
  • Factor the singleton into two or more classes: sometimes the options above are not available. But it is still possible to reduce the functionality of the singleton and provide them with two or more classes. A few of these classes can be non-singletons, which are easier to test. While this won’t solve the whole problem, it may simplify development and testing of the application.
  • Make the singleton as small as possible: As a last resort, use the tactic above to remove all the functionality that is not strictly necessary from the singleton. Even if you cannot test the singleton in isolation, you make it very small and easier to understand. This also remove the temptation of adding even more functionality to an existing singleton.

Conclusion

The singleton pattern has a number of deficiencies that make it difficult to integrate with other programming practices. Therefore, it makes sense to restrict its use only to situations when it is strictly necessary. You should investigate some of the ideas above to reduce or eliminate the use of singletons in your code, and as a result, improve the testability of the application.

Further Reading

The Gang of Four book is the original source for everything design patterns. You should check carefully the rationale for using singletons.

 

Similar Posts:

Similar Posts

77 Comments

  1. Wonderful article! I like to see people beyond me that also point to the seminal works on the methodologies most people talk about nowadays, as you did referring to GOF book.

  2. Another important alternative is Monostate Pattern. Uncle Bob (Robert C. Martin) described it in an (pdf) article at Objectmentor.

  3. Having read this I believed it was really informative. I appreciate you taking the time and energy
    to put this informative article together. I once again find myself personally spending
    a lot of time both reading and posting comments.
    But so what, it was still worth it!

  4. I was extremely pleased to discover this page.
    I wanted to thank you for your time due to this fantastic read!!
    I definitely appreciated every part of it and i also have you book-marked to look at new stuff in your blog.

  5. Thanks a lot for sharing this with all of
    us you actually know what you’re talking approximately! Bookmarked.
    Please additionally talk over with my website =). We could have a hyperlink trade agreement among us

  6. Fantastic post however , I was wanting to know if you
    could write a litte more on this topic? I’d be
    very grateful if you could elaborate a little bit more.
    Bless you!

  7. You’ve made some decent points there. I looked on the web
    to learn more about the issue and found most individuals will go along with your views on this website.

  8. You could certainly see your skills in the work you write.
    The world hopes for more passionate writers like you
    who are not afraid to mention how they believe. All the time go after your heart.

  9. Wonderful goods from you, man. I’ve understand your stuff previous
    to and you are just extremely great. I actually like what you have
    acquired here, really like what you are stating and the way in which you say it.

    You make it entertaining and you still take care of to keep it
    smart. I can’t wait to read far more from you. This is actually a terrific web site.

  10. Hey There. I discovered your blog using msn. That is an extremely smartly written article.
    I’ll be sure to bookmark it and return to learn extra of your useful info.
    Thanks for the post. I will certainly comeback.

  11. I don’t know whether it’s just me or if perhaps everyone else experiencing issues with your site.

    It appears like some of the text within your posts are running off the
    screen. Can somebody else please comment and let me know
    if this is happening to them as well? This could be a problem with my internet
    browser because I’ve had this happen before.
    Thanks

  12. Greetings I am s? thrilled ? found ?our webpage,
    ? really f?und you by mistake, w?ile ? was l?oking on Yahoo for something el??, Rega?dless I
    am here now and w?uld just l?ke to say many thanks for a marvelous post ?nd a al? r?und intere?ting blog (I als? love
    the theme/design), I ?on’t ?ave time to look over it a?l at the m?ment but I ?ave
    saved it ?nd al?o added ?n your RSS feeds, so ?hen I ?ave time ? wil? be back to ?ead ? l?t more, P?ease d? keep up t?e excellent
    job.

  13. Fantastic goods from you, man. I’ve understand your stuff previous to and you’re just
    too wonderful. I really like what you have acquired here, really like what you’re stating and the way in which you
    say it. You make it entertaining and you still
    care for to keep it smart. I can’t wait to read far more from you.

    This is actually a great site.

  14. ?ello t?ere! I co?ld have sworn I’?? b?en to th?s website b?fore ?ut ?fter browsing t?rough ?ome of the
    post ? realized it’s new to m?. Any?ow, I’m definit?ly
    glad ? fo?nd it ?nd I’ll be book-marking ?nd checking ?ack
    frequently!

  15. After I originally commented I seem to hav? clicked the -Notify
    m? w?en new comments are ?dded- checkbox ?nd from now on every time a comment is
    added ? get fo?r emails wit? the s?m? comment. Per?aps there ?? an easy method ?ou ??n remove me from that service?
    Kudos!

  16. ?ell? would y?u mind letting m? know which hosting company y?u’re ?orking ?ith?
    ?’v? loaded y?ur blog in 3 complet?ly d?fferent browsers ?nd ? mu?t ?ay thi? blog
    loads ? lot quicker t??n most. ??n you
    suggest a good hosting provider at ? honest price?
    Cheers, I ?ppreciate it!

  17. I ?on’t even understand how ? stopped up right
    here, ?owever I ?elieved this publish was good. I ??n’t realize who you ?r? but certainly you’re going to a w?ll-kno?n blogger if you h?ppen to aren’t a?ready.

    Cheers!

  18. Hey th?re! I know t?is ?s kind of off-topic however ? ne?ded t? as?.

    Doe? running a ?ell-established website ?ike yo?rs require ? ?arge amount of work?

    I’m ?ompletely ne? to blogging ?owever ? do write ?n my journal daily.
    ?’d like t? start a blog s? I ?ill be able to share my
    personal experience ?nd views online. ?lease l?t me know if you h?ve any kind of ideas
    o? tips f?r brand new aspiring blog owners.
    ?ppreciate it!

  19. Aw, t?is was an exceptionally good post. Finding the tim? and actual effort t? produce a g?od article… ?ut w?at
    can I say… ? hesitate a lot ?nd ?on’t manage to get anyth?ng done.

  20. Hi i am kavin, its my first time to commenting anyplace, when i read this paragraph i thought i could
    also create comment due to this brilliant piece of writing.

    Take a look at my website: ?? ????

  21. naturally like your web site however you need to check the spelling on several
    of your posts. A number of them are rife with spelling problems and I
    find it very bothersome to tell the reality then again I’ll certainly come again again.

    Here is my blog – savastan0 cc

  22. I don’t even know how I ended up here, but I thought this post was good.
    I do not know who you are but definitely you’re going to a famous blogger if
    you are not already ;) Cheers!

    My web site :: savastan0. cc

  23. Excellent beat ! I would like to apprentice while you amend your web site, how could
    i subscribe for a blog site? The account aided me a acceptable deal.
    I had been tiny bit acquainted of this your broadcast provided bright clear idea

    Have a look at my website :: savastan0 cc

  24. Hey there! I’m at work browsing your blog from my new iphone 3gs!

    Just wanted to say I love reading through your blog and look
    forward to all your posts! Carry on the great work!

    Feel free to surf to my web site; savastan

  25. Thanks for one’s marvelous posting! I certainly enjoyed reading it, you might be a great author.
    I will be sure to bookmark your blog and will often come back very soon. I want to encourage yourself to continue
    your great work, have a nice evening!

    Here is my web site blackpass info

  26. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point.
    You obviously know what youre talking about, why throw away your intelligence
    on just posting videos to your weblog when you could be giving
    us something informative to read?

    Here is my web blog; prozoneshop

  27. It’s perfect time to make a few plans for the longer term and it’s time to be happy.
    I have read this post and if I could I desire to counsel you few
    attention-grabbing things or suggestions. Perhaps you can write subsequent articles relating to
    this article. I desire to learn even more things about it!

    My blog post: savastan cc

  28. A fascinating discussion is worth comment. I do believe that
    you need to write more about this subject matter, it might not be a taboo matter but typically folks don’t discuss
    these subjects. To the next! All the best!!

    Also visit my page: bclub cm

  29. hello there and thank you for your information – I’ve
    certainly picked up anything new from right here.
    I did however expertise several technical issues using this web site, as I
    experienced to reload the web site lots of times previous to I could get
    it to load correctly. I had been wondering if your web hosting is OK?
    Not that I am complaining, but slow loading
    instances times will often affect your placement in google and can damage
    your high-quality score if ads and marketing with Adwords. Well I am adding
    this RSS to my email and could look out for a lot more of your
    respective interesting content. Ensure that you update this again very soon.

    Also visit my blog post; black pass

  30. I got this website from my friend who told me regarding this site and at the
    moment this time I am browsing this web site and
    reading very informative articles here.

    Also visit my web-site … savastan0

  31. It’s a shame you don’t have a donate button! I’d
    definitely donate to this excellent blog! I suppose for now i’ll settle for book-marking
    and adding your RSS feed to my Google account.
    I look forward to new updates and will talk about this website with my Facebook group.
    Chat soon!

    Review my website: savastan0

  32. It’s really a great and helpful piece of information. I am satisfied
    that you simply shared this helpful info with
    us. Please keep us informed like this. Thanks for sharing.

    Here is my web site findsome

  33. Very nice post. I just stumbled upon your weblog and wished to say that I have truly enjoyed surfing around your blog posts.

    In any case I’ll be subscribing to your rss feed and I hope
    you write again very soon!

    Stop by my webpage: findsome

  34. I’m not sure exactly why but this site is loading
    very slow for me. Is anyone else having this issue or is
    it a problem on my end? I’ll check back later and see if the problem
    still exists.

    My blog … findsome cc

  35. With havin so much written content do you ever run into any problems of plagorism
    or copyright violation? My site has a lot of completely unique content I’ve either authored myself or outsourced but it looks like a lot
    of it is popping it up all over the internet without my agreement.
    Do you know any techniques to help reduce content from
    being ripped off? I’d genuinely appreciate it.

    My blog :: russianmarket

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.