Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I'm giving up singletons because hidden dependencies are a source of bugs. Let me make it more concrete:

Suppose classes A, B, and C use singleton class S, and S has state. Via the hidden dependency on S, it's possible for A, B, and C to affect each other without explicitly calling each other's methods.

As a programmer, you can take those hidden interactions into account and still have a relatively bug-free program. But it's one more thing you have to hold in your head. When you return to the project six months later, you have to read through the internal code of A, B, and C to see these interactions; the public APIs don't reveal them. You spend more time figuring out how the objects interact, and there's a greater chance you'll fail to notice an interaction.



In the general case, I agree. But for a very few things, singletons make fine sense. Usually in small programs where you can draw the entire object graph on a single piece of paper, and where all the features it will have are known up front.


Certainly! Tiny programs are the exception to most best practices. (Not security best practices, but I digress.) I write a lot of little programs, and they're certainly not all works of art. Sometimes you need to bang out a tiny program quickly, and it's never going to become a maintenance burden. In which case you can use any pattern or anti-pattern you like.


That sounds like a very black/white way to say it. I don't agree that using a singleton in small programs is an anti-pattern. The world is much more gray than that.


I said you can use anti-patterns in small programs, not that singleton is an example of an anti-pattern. I don't believe singleton is so terrible as to be an anti-pattern, even for big programs. I just think it has some downsides that are really worth considering before you use it.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: