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

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

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.