Patterns I Hate #1: Singleton

57

This entry inaugurates a new series on patterns that I hate. Hate is a strong word, perhaps a better name would be “patterns that I’ve frequently seen lead to ruin”. But that seemed too long.

Anyhow, the singleton pattern is the hands-down #1 pattern that can lead me to froth at the mouth. When a programmer first stumbles on GoF, Singleton seems to be the pattern that they first latch on to because it’s so easy to understand (just one class). Novice programmers doing their first design will often break out subsystems and access them via singletons.

Why is Singleton evil?

  1. Hides dependencies – A component that uses one or more singletons is hiding crucial information about your dependencies. It doesn’t take long for calls to a singleton to creep through your code base like kudzu, slowly attaching itself to every class in the system. Exposing that dependency forces you to think about it as you use a component. It also makes it more reusable as the caller can understand its requirements and how they might be satisfied.
  2. Hard to test – The hidden coupling of users on a singleton makes testing a nightmare as there is no way to mock out or inject a test instance of the singleton. Also, the state of the singleton affects the execution of a suite of tests such that they are not properly isolated from each other.
  3. Hard to subclass – Since initialization occurs in a singleton in static code, it is not amenable to subclassing because subclasses inherit the initialization code without the chance to override it.
  4. It’s a lie! (in most Java systems) – Singletons in Java are based on static variables, which are held per-classloader, not per-VM. In most systems of any complexity these days (any based on an app server, OSGi, Eclipse, plugins, etc) many classloaders will be involved. In that case, it is quite easy for two plugins to create their own instance of a singleton. Sometimes this is done by design and is desirable. But it’s also easy to screw up. It’s also usually critical that the singleton get created in the right classloader, which can make lazily constructing the singleton tricky.
  5. A singleton today is a multiple tomorrow – It’s not at all unusual to discover that you now need 2 or more of something you previously only needed one of. Hard-coding the singleton pattern into your code makes it impossible to satisfy that demand later. This probably seems really weird if it hasn’t happened to you, but it has happened more than once to me.

What is the alternative?

First, it is important to separate the “need for one of something in my system” from the “singleton pattern”. It’s perfectly reasonable to want one of something but to avoid using the singleton pattern. In other words, the problem is in the pattern, not in the goal.

When a singleton seems like the answer, I find it is often wiser to:

  • Create an interface and a default implementation of your singleton
  • Construct a single instance of your default implementation at the “top” of your system. This might be in a Spring config, or in code, or defined in a variety of ways depending on your system.
  • Pass the single instance into each component that needs it (dependency injection)

This alternative will give you the effects of a singleton, but makes the dependencies clear in the components that need it, allows a singleton to be mocked (via the interface), subclassed, proxied, and tested.

But I already have a bunch of singletons in my code!

Sometimes, you’ll have a system (built by you or someone else) that is heavily dependent on some singletons. Often, you will find this annoying as you try to test and/or add functionality to the system. To refactor the singletons out of your system, you need to start from each point of use and allow the singleton to be set as a dependency on the component using it, rather than calling to the singleton’s getInstance() method. Doing so moves the singleton access (but not use) up one level. Repeat until the singleton’s getInstance() method is called in as few places as possible (ideally one).

At this point, all components in the system declare their dependence on the concrete singleton class and that singleton class is instantiated at a very few points at the “top” or your architecture (then passed down through the systems). Next, it’s time to apply some classic refactoring. Most importantly, we want to change the concrete singleton class into an interface and move the existing concrete implementation into a new default implementation class implementing the interface. Finally, you’ll probably want to cleanup the calls to getInstance() with either a call to new the concrete default implementation or a factory method that can do that for you.

This transformation should make all of your components dependent on an injectable, interface-defined component, which is easy to mock or swap in during unit testing of the component itself. It also typically makes testing of the concrete singleton implementation itself a breeze compared to the prior implementation.

Note that the first phase of bubbling the singleton instantiation up through the architecture can be done as slowly as needed and does not need to be done all at once. You’ll find the second phase is fairly easy with any modern IDE once you get to that point.

But I really, really, really want to use a singleton

There are still some cases where singletons are a valid choice.

One is logging. Logging is so pervasive that unless you use some fairly heavy-handed dependency injection or AOP, it is not feasible to inject every class in the system with a logger. Instead, this is a case where using static methods or singletons are probably worth the compromise.

Another common use is to obtain a handle to a service locator (think JNDI) that knows how to access everything else. This is actually one way to change your entire system from using many singletons to using one singleton that knows how to find the others. This is a valid technique that addresses some of the inherent problems (mockability, testing) with singletons and may be a less invasive change to a legacy code base.

Swing or other client-side UIs are another case where singletons may be a valid choice. In the case of a Java desktop app, it is likely that you have more complete control over your deployment environment than you do in a server-side application. In this case, it can be acceptable to have a manager class managing some state as a singleton in the VM. However, my preference would be to go the extra step to expose that dependency.

If you do really need to use a singleton, please make sure you initialize it safely!

This concludes the first pattern I hate. I’ll be back soon to talk about another.

Comments

57 Responses to “Patterns I Hate #1: Singleton”
  1. Nico Mommaerts says:

    “Note that the first phase of bubbling the singleton instantiation up through the architecture can be done as slowly as needed and does not need to be done all at once.”
    Took me more as a year on my last project ;)

    Anyways, nice post. I often find it hard to explain to customers why the singleton pattern is not always what you want, something I sense intuitively based upon previous experience. I’m gonna tag this post on my delicious for future reference ;)

  2. Alex says:

    Yep, it’s taken me as long as several major releases to fully extract ancient and intertwined singletons from components before. If you can just keep pulling those dependencies up, you’ll eventually free yourself.

  3. Brian Button says:

    Hi, Alex,

    Check out two blog posts from about 3 years ago:

    http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx
    http://www.agileprogrammer.com/oneagilecoder/archive/2004/08/17/2845.aspx

    I couldn’t agree with you more. In fact, I already have agreed with you in those blog posts :)

    – bab

  4. Alex says:

    Great links, Brian! I’m glad I’m not alone in the wilderness. I’m proud to say that on my current project we have NO singletons. Well, none following the singleton pattern at least; we do have a couple registry type classes but they just happen to be created once.

  5. troels says:

    I wouldn’t say that accessing a registry through global means (Singleton) is a good choice of design. It reduces the number of singletons, but it’s still sub-optimal. I always pass my service locator around (dependency injection) to the classes, which needs it.

  6. Muhammad Ishaq says:

    Hi,

    I am not a hard core design patterns programmer but:

    “There are still some cases where singletons are a valid choice.”

    and I guess singletons are really made for those cases, If we are using them for anything else, it’s a fault in our design, not the pattern. :)

    Regards,
    MI

  7. Alex says:

    @troels: I agree completely. But using a singleton service locator (hello JNDI) is a workable solution, if not an optimal one.

  8. Matt says:

    Great article. I used to think singletons were the cat’s meow and used them everywhere. After a while I realized pretty much everything you have said about them. But I still find factories to be valid and useful in some cases, and those are essentially singletons. But again, get the object from the factory then pass it on to the object that needs it as dependency injection.

  9. Ross says:

    The uses of singletons that you mention can be replaced by static methods. The only time I’ve used it was for a tree implementation, where Branch and Leaf inherit from Node, and Leaf is a singleton.

  10. Matt says:

    @Ross: static methods are just as bad as singletons in this case. They can’t effectively be mocked, the creep into your code, etc etc.

  11. Alex says:

    @Muhammad: You are, of course, correct. Singleton is a tool just like all design patterns and the trick is knowing when to apply it. My point is that Singleton is misapplied and over-applied frequently.

    @Ross: I agree with Matt that static methods are just as bad a solution for many of the same reasons (can’t mock, can’t subclass, etc). Not that static methods are inherently bad, as they are useful for many things, but rather they have many of the same impacts on your code, making it difficult to test, maintain, and evolve.

    @Kevin: Thanks for the link, good stuff.

  12. Alex says:

    Someone on reddit posted this link from Steve Yegge about singletons. Steve is way smarter than me and knows more about languages than I will ever know, so check it out.

  13. Dan Sickles says:

    “Singleton? We don’t need no stinkin’ singleton: the Borg design pattern”:

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531

    Scala uses ‘object’ instead of ‘class’ for one of something. See the code exmple:

    http://www.scala-lang.org/

    Can’t help but think of this:

    “Patterns are signs of weakness in programming languages.”

    http://blog.plover.com/prog/design-patterns.html

  14. You forgot the most important reason!

    Singletons are the object oriented equivalent of a GLOBAL VARIABLE!

    Everything that can be said about global variable’s evilness can be said about singletons. And, they will lead you to ruin everytime.

    In school you were docked 50 points for using a global variable. Which basically means you fail if you use one. I wish we could dock 50% pay from developers if they used them.

  15. I disagree with using singletons in Swing Apps. Creating singletons that manage your application state will get you into trouble. The classic problem is say today your app consists of a single frame, and that frame interacts with a singleton for state. Well tomorrow you want to allow the user to open two frames of your application, like a web browser. Well in order to store that state for the second window you need 2 instances of your manager class. Bam. You just bought yourself a lot of refactoring because you choose to use a singleton. Don’t do it. Learn from my mistakes. ;-)

  16. Francisco J. Carriedo says:

    In my experience, one valid usage of a singleton is an ApplicationContext (or the equivalent) object used as a factory. Preferably no more than 1 singleton per application.

  17. Nice and informative, I assume it’s the first pattern people learn since it’s the one that the most closely resembles their old world of thinking in “global access”… ;)

    It’s important to get enlightened the BAD things about this patterns in fact…

    .t

  18. Matt says:

    Shouldn’t “Hard to subclass” be “Impossible to subclass?” I’ve seen variations on the implementation of a singleton but they always have a private constructors. The compiler will error when you try to subclass one.

  19. Alex says:

    @Matt: Oh, you can definitely find people out there with examples of how to do it, but they are really kludgy, as you’d imagine.

  20. Matt says:

    Kludgy would probably be an understatment :).

    But you are right, just make the constructors protected. After looking in my copy of design patterns it’s actually listed as a positive consequence of the pattern.

    Personally, I feel that it’s not in the true spirit of being a Singleton if the base wasn’t abstract. It would seem unnatural to have two Singletons with an is-a relationship.

  21. Pat Farrell says:

    I’m confused. So we are supposed to have a factory that hands out objects, perhaps from a cache or pool. All of the objects have protected constructors. This I can follow. But doesn’t the factory have to be a singleton so it can have a static pool of objects?
    And isn’t the factory then subject to the same problems of multiple class loaders creating multiple pools.

    How far does one have to go to unravel this onion?

  22. Alex says:

    @Pat: I’ve lost track a little as to what you’re referring to (the article or the comments). Factories don’t have to be singletons, although if they are managing pools you would probably want them to be to increase the effectiveness of the pool (although I’d recommend testing thoroughly whether a pool is even worth it).

    Regarding the classloader issue, assembling the application from pieces using dependency injection typically allows you to do configuration top-down, which has a nice side effect of allowing you a lot of control over which classloader is used. In factories, it is typical to either use the thread context classloader or to pass a classloader into the factory for the purposes of creation. The problem with lazily loaded singletons is that anyone at any point in your application could be the first one to create the singleton and that makes it very difficult to control which classloader is the one that actually instantiates it.

  23. Pat Farrell says:

    “lost track a little as to what you’re referring to (the article or the comments). Factories don’t have to be singletons”

    Sometimes, you really need just one instance. Using a factory allows you to make the Thing not be an instance, but then the Factory must be.

    When you need to have one and only one of something, say a GrandConnectionObject, you can have a Factory make it, but then the Factory has to manage that there is one and only one GrandConnectionObject.

    The dependancy is a bit clearer, and you can hid the artifact that there really is only one GrandConnectionObject, but the Factory has to be static, aka a Singleton.

    So the factory is just syntactic sugar for the singleton.

  24. Alex says:

    Singleton is made up of two parts: creation and access. The creational part covers how a singleton creates its own instance (maybe eagerly, maybe lazily). The access part covers how users of the singleton instance get the instance.

    Yes, factories are another creational pattern and can be used to create instances and in some sense share many common traits with singletons. Replacing a static call to Singleton.getInstance() with a static call to Factory.newInstance() addresses none of the evils of Singleton. I’ll agree with you there. But that’s not what I’m suggesting.

    You really need to address the question of access as that is where the problems lie. You must replace static calls to a Singleton (or Factory or in some cases even new) with either 1) an attribute that can be set or 2) a call to an instance. #1 is effectively dependency injection and #2 is effectively Service Locator. Both techniques allow you to write a component that has more flexibility with how the instance is created because the component is not creating it and is not calling a static fixed method that creates it.

    You want to then bubble this idea up to the top (or other natural application assembly point) in your system. At that point, you can simply new up the objects that make up your system. If you only want one of something, create only one of it! You don’t need the Singleton pattern to do that. If you want, you can call a Factory to create the instance. But you do that once at the top instead of many times in many components. Or if using a Service Locator pattern, the top of your app can assemble all the instances involved and set them into the Locator.

  25. Feca says:

    This is a not so evil Singleton sample (this is an angel singleton without the getInstance method):

    class Singleton {
    private static Singleton instance = null;

    public static Singleton getInstance() {
    synchronized (Singleton.class) {
    String className = System.getProperty(“Singleton”, “Singleton”);
    if (instance == null) {
    try {
    Class classObject = Class.forName(className);
    instance = (Singleton) classObject.newInstance();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    return instance;
    }

    public Singleton() {
    if (instance != null) {
    throw new RuntimeException(“More than one instance has created!”);
    } else {
    instance = this;
    }
    }

    public void show() {
    System.out.println(“Singleton”);
    }
    }

    class SingletonExtended extends Singleton {
    public SingletonExtended() {
    super();
    }

    public void show() {
    System.out.println(“SingletonExtended”);
    }
    }

  26. Gabriel C says:

    ” It’s not at all unusual to discover that you now need 2 or more of something you previously only needed one of. Hard-coding the singleton pattern into your code makes it impossible to satisfy that demand later. This probably seems really weird if it hasn’t happened to you, but it has happened more than once to me.”
    Hmm.. I have to say WRONG :-) That’s one of the intents of singleton pattern!!! Control the number of instances… if you need 2 just create 2 inside the singleton!
    Check the GoF book…

  27. DAR says:

    FYI – you gave some bad advice here. It has been well known for some time that double-checked locking is *not* a safe way to initialize singletons. (See: http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html)

    The “Initialization on demand holder idiom” (http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom) should be used instead.

  28. Alex says:

    @DAR: I think you’ll find if you actually read it that the blog doesn’t actually mention double-checked locking or give any advice about it. It does refer to another blog entry of mine about double-checked locking which talks about this in great detail (including the initialization on demand holder idiom). There is an example given by someone else in the comments above, but that example doesn’t use double-checked locking either.

    So I’m not sure what you’re talking about.

  29. DAR says:

    @Alex: Whoops! You’re right. I didn’t actually read the referenced link; I just saw that the URL had the words “double checked locking” in it and assumed that you were recommending that approach.

    After reading it, I see that it’s actually a rather in-depth discussion of the whole DCL issue, and does conclude with IODH.

    My apologies!

  30. Nigel says:

    Sorry for a late comment, but you have provided the clearest and most succinct description I’ve yet seen of the case against, so I wanted to try out some counter-arguments:

    1. Hides dependencies

    But isn’t this a Good Thing? I’d always thought hiding implementation details was part of information hiding. If a component A uses component B to do it’s job, should that be exposed to the calling code? I’m not saying it shouldn’t be clearly visible, but the visibility should be at the IDE component browser level, not mixed up with my application code. If component A chooses to change its implementation to use component C instead, I don’t want to change all my calling code.

    2. Hard to test
    ‘there is no way to mock out or inject a test instance of the singleton’
    But that isn’t thay easy to change, by, for example, providing a setter as well as a getter for the instance, or configuring the singleton factory method with the type to instantiate?

    3. Hard to subclass
    Why? If the singleton exposes an instance of an abstract class, and the constructed type is configurable, I can sub-class easily enough.

    4. It’s a lie
    True. But most example of singleton’s I’ve seen don’t really have to be singletons. In fact singleton is probably a misnomer in many cases – the singleton instance is a global variable used instead of dependency injection.

    5. A singleton today is a multiple tomorrow
    Yes – I’ve been caught that way too. But not often enough to dismiss singletons as a technique.

  31. Alex says:

    1. In general, I’d say no, it’s not a good thing to hide your dependencies at the class level. I generally expose dependencies for injection and have found it to create systems that are easier to test and evolve.

    At the component/subsystem/layer boundary, it depends. If your system is composed of alternating hard and soft layers for example, you’ll find the soft layers are the perfect place to dynamically choose what gets injected in the hard layer below.

    2. It seems to me like either of these techniques means opening up your code to non-longer actually be a singleton. But perhaps more seriously, it assumes that your test actually knows what singletons need to be substituted. Since those singleton uses are hidden (possibly many layers away from the code under test), it’s quite easy to miss one. Using dependency injection exposes those dependencies and forces you to deal with them.

    3. Where does the static singleton accessor method and instance live? If it’s on the abstract or base singleton class, then you must hard-code the accessor to one particular (sub-class) instance. And then what point is there in being able to create subclasses if you are hard-coded to only using one of them?

    Your other alternative is to repeat the static accessor method and instance on each subclass and have your code bind to not one but many singletons (an even messier coupling problem). In doing so, you will also expose the singleton’s construction so that someone could subclass it and subvert the intended singleton nature.

    4. Then why use the singleton pattern? I’d rather have my structural assembly choices collected at the top of the application, either in code (often sufficient) or injected by something like Spring or Guice.

    5. My experience has been that if you maintain the code long enough, this problem ultimately occurs. Inevitably, this is a design decision that ties your hands and gives you no way to fix it when it becomes an urgent problem.

    I gave up the singleton pattern 5 or 6 years ago and haven’t used it since. I haven’t missed it at all.

  32. Nigel says:

    Alex – thanks for the responses.

    1. Interesting. You may be right, but I’m going to need a slight mind-set shift, I think.

    2. Mostly I’m not too worried about abuse of the mechanism, but I take your point that the dependencies are much harder to track.

    3. Well, in some cases hard coding the type may be ok – I was really making this argument to say that you could plug in a different implementation class without much impact on the calling code. And you could make the type to be instantiated a static property of the abstract class if you wanted run-time flexibility. However it doesn’t feel entirely right, I must admit.

    4. Usually because they were in the code when I got it, though I may have added a few myself. But my concern with the alternative is that passing dependencies all the way up through the layers may be worse. The dependencies may not have anything to do with the business logic, and I don’t like the idea of constructors with a mix of domain objects and component plumbing.

    5. I guess I’m just going to have to try a project where I ban all singletons, and see how it goes.

  33. Alex says:

    4. I understand your concerns on this. Generally, I find that when it feels like you have to pass lots of dependencies around, the problem is that your classes are not separating responsibilities well. It’s usually helpful to step back and ask yourself whether those dependencies really should be in all those classes or whether there is some other setup that would minimize those. In this respect, singletons can hide bad design by allowing you to cheat. Exposing those singletons as dependencies can make things bad at first but show you a path towards a better design. As a consequence of reworking responsibilities, you will also make your code more testable.

    If you really want to avoid the injection mess, you can instead use a DI framework like Spring or Guice. Then you basically filter your construction through a framework that uses a configuration (defines partly or completely separately) to properly instantiate objects and inject instances.

  34. Misko Hevery says:

    Hi Alex,

    Glad to hear that you are keeping up on top of those singletons. I personally find that Singletons are Global State in sheep’s clothing, and that Singletons turn your code into Pathological Lairs. But I know that you already know that.

    – Misko

  35. Adeel Shahid says:

    I have written some code to expand on idea of Abstract Singleton Pattern comments in code explain stuff. It’s easy to criticize on the singleton pattern but examples like below must be given to elevate understanding of Design Patterns specially for beginners like me, otherwise you don’t really get the meaning/message through


    interface iPreference {
    public function getProperty($key);
    public function setProperty($key, $value);
    }

    final class Preference implements iPreference {

    private static $instance;
    private $properties;

    private function __construct() { }
    private function __clone() { }

    public static function getInstance() {
    if (empty(self::$instance) || !(self::$instance instanceof self)) {
    self::$instance = new Preference();
    }

    return self::$instance;
    }

    /** Implementing iPreference interface */
    public function getProperty($key) {
    if (isset($this->properties[$key])) {
    return $this->properties[$key];
    }

    throw new Exception('property not found');
    }

    public function setProperty($key, $value) {
    $this->properties[$key] = $value;
    }
    }

    $pObj = Preference::getInstance();

    $pObj->setProperty('color', 'yellow');

    /**
    * Now when passing Preference object $pObj to another class or constructor
    * that class or constructor should accept $pObj as a IPreference
    * helping you flexibly change Singleton later on if you run into extensibility problems
    */

  36. Dizzy says:

    Somehow, all of this singleton-hatred sounds a bit Cargo Cult. It’s quite easy to refactor your singleton-using code to acquire the wanted object “normally”, without using instance(). It also leads to less change propagation than passing every object you instantiated in constructor arguments all over the place.

    Singleton is a “cheap” way of doing dependency injection, very applicable when you are doing new development or refactoring. It’s not like it permanently screws up your source code.

  37. Peter Kofler says:

    [...] What’s your favourite design pattern? Mine is the Singleton pattern. No, I’m joking, I hate it. Alex Miller hates it too and explained some time ago why it’s so hateful. (At my previous working place one third of all classes was dependant on singletons. It was awful.) I can’t stand them. I’m getting sick when I see one. Therefore I’m sure that Singletons Are Evil. [...] Singletons Are Evil T-shirt [...]

  38. codematrix says:

    Every argument on this site against singtions is complete wrong and has been debunked by me. I just did a presentation on “How to Make Classes Testable” and I how I not solved the insane notition of TOOD (Testable Object-Oriented Design) in how it breaks OO and more importantly the crap talk about singletons. I developed this concept called “Class Dependency Definition Injection” CDDI that not only solves the Singleton problem but solves the need to overoad constructions and methods to allow unit tests to inject dependencies. The audience were impressed by a simple construct of CDDI and how it solves the need for TOOD and allowing you to use Singletons.

    Now I will agree that some developers create very bad singletons but that’s not the fault of the pattern but the developers lack in experince. My version of the Singleton alters the original design pattern a bit but it allows Singletons to be able to Inject testable versions for mocking and more importanly, allows singletons themselves to be directly tested. Isolation is key and CDDI solves this problem during testing.

    I’ve been developing software for over 25 years, I’m a big fan of clean code but I hate arguments like this on this site. I was in the same boat as you all about singletons and the need for TOOD but it bugged me when I had to alter my classes quite a bit to make it testable. CDDI keeps my class simple, natural and more importantly testable. Believe or not CDDI is itself a Singleton!

    If anyone is interested in knowing more, please contact me. I’m charging anyone but I’m sick and tired of the alternative and developed my own version with amazing success.

    codematrix

  39. Chris Sherlock says:

    You use Spring as your IoC, then you are almost certainly going to be creating mostly singleton scoped objects. Just sayin’

  40. Ken says:

    I Googled “I hate singleton” after spending about 3 hours trying to create multiple objects and noticing that I was only getting 1. It took me a while to even realize that when I was creating the objects it was using the singleton pattern (I didn’t write the code originally). So my google search result lead me here. And after reading this, I can safely stop banging my head against the wall ><

Trackbacks

Check out what others are saying about this post...
  1. [...] I came across a very good blog article today at http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/. It’s about Singleton Pattern. [...]

  2. [...] Apparently my previous pattern posts on Singleton and Template Method hit a nerve based on comments and traffic – thanks for reading! I’m now moving the series from patterns that I hate to patterns that I simultaneous love and hate, because hey, I’m a complicated man (and no one understands me but my woman). [...]

  3. [...] Cedric has a nice post up defending design patterns. I have personally been quite vocal in criticizing several popular patterns lately (see Singleton, Template Method, and Visitor), so I guess I bear a partial amount of the heat. I’ve tried in my posts (despite their inflammatory titles) to point out not really why the pattern sucks but more where it is commonly poorly applied (especially in Java) and how to address those problems with concrete suggestions. At least that was my goal. :) [...]

  4. [...] Having come across Alex Miller’s blog, I’ve enjoyed a number of his posts. However, whereas I am definitely in-line with his dislike of the Singleton pattern, I couldn’t agree with his conclusions on the use of the template pattern. 1. Communicates intent poorly – The template method pattern is often used as part of the effective API in some mini-framework where the framework user is expected to subclass the template class. My experience has been that it is difficult to communicate that usage intent to users of the framework. Often the template class has some non-private methods that are exposed for use by the framework but are not intended to be used by the framework user, some that are intended to be overridden, and some that are both. Also, you may need to say whether the super’s version of the method can, should, or must be called. Communicating all that clearly is impossible in an API of any complexity. [...]

  5. [...] Ett annat typfall på hur man gjort innan DI är användande av fabriksmetoder som i Singleton pattern (även känt under synonymet Evil singleton pattern). Ett av huvudproblemen i användningen av detta mönster är den dåliga testbarheten pga att statiska metoder används som är svåra att byta ut under test. [...]

  6. [...] cheat us from design perspective too – here, here and [...]

  7. Foretrukne patterns…

    Patternkatalog I motsetning til Forslag til løsning (som skal inneholde egenproduserte løsningsforslag), er denne siden ment å inneholde en oversikt over kjente patterns også våre egne ting,……

  8. [...] could use the singleton pattern to restrict the number of instances to one, but that approach is frowned upon these days.  Dependency injection is the more politically correct alternative, just pass your [...]

  9. [...] the code harder to maintain and test and its also referred to as ‘anti-pattern’ now [4][5][6]. On the other hand the creation of instances is handled by DI container and the dependent [...]

  10. [...] Alex Miller. Patterns I hate #1: Singleton, July [...]

  11. [...] standard Singleton implementation (that static getInstance method) is severely flawed. Unless you are writing device drivers, there is almost no excuse to touch a Singleton with [...]

  12. [...] the code harder to maintain and test and its also referred to as ‘anti-pattern’ now [4][5][6]. On the other hand the creation of instances is handled by DI container and the dependent [...]

  13. [...] In Java, it’s common practice to define the Singleton class as final to prevent extending it (some people insist that this behavior is rather an anti-pattern. Read here for more information: http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/). [...]

  14. [...] Alex Miller: Patterns I Hate [...]