4 ms·
Steve Yegge: Singleton Considered Stupid
- Tichy 18y agoIronically, my experience was that everybody seemed to only understand the factory pattern. Wherever I worked, people loved using factory, whether it made sense or not.
- sah 18y agoI can't stand it when people use Factory in Python. In Python, classes are objects -- you can just pass a class into a function as a parameter!
- globalrev 18y agoyou cant in java!?
- Tichy 18y agoOf course you can. I don't see how passing around classes could replace the factory pattern? In Java these days usually Spring is the factory...
- nostrademons 18y agoUsually you use the factory pattern because you want to customize the concrete type of object that's instantiated, correct? In Python, you'd just pass the class itself in, and since every class is a callable that constructs an instance of itself when called, you can use that to control instantiation: class Foo: ... class Bar: ... def factory_client(cls): my_instance = cls() ... return my_instance foo_instance = factory_client(Foo) bar_instance = factory_client(Bar) You can do the same thing in Java with Class objects and reflection (Class.newInstance() etc.), but reflection is a.) slow and b.) clunky, so most Java programmers create factories instead. Parameterized classes are much more a part of Python culture than Java culture.
- Tichy 18y agoWell thinking about Spring, it does a lot of wiring behind the scenes. How would you do that with Python? What does the factory_client method do? I don't think Java Reflection is a/the problem.
- nostrademons 18y agofactory_client does whatever you want it to do - it's just the method that would call your Abstract Factory or Factory Method or whatever. I've never used Spring, but I assume that the wiring it does is similar to JSF managed beans, eg. you give it an XML config file and it takes care of creating the appropriate Java objects from that. As for how you'd do it in Python - you wouldn't. To quote Phillip Eby: "XML is not the answer. It is not even the question." http://dirtsimple.org/2004/12/python-is-not-java.html http://dirtsimple.org/2004/12/python-is-not-java.html That's because XML is usually easier to write than Java but harder to write than Python, so you're better off just writing the Python. You'd write your classes, and then stick them in a data structure somewhere. You could even use the package structure of your app as that data structure - have the client code receive a module (modules and packages are first-class in Python), then use getattr to pull out the class object. Then when you have a class object, you call it to create a new instance. I suppose if you want some security guarantees, you'd explicitly specify the classes that may be passed in to the method. For example, in my own app, I have a bunch of classes that essentially represent language constructs in a visual domain-specific language, each of which has a "default" value so that when the user's clicking away they don't have to type in code from scratch. I wanted to expose these defaults to JavaScript, the language of the UI. So I put together a dictionary of the classes that I want exposed, then loop through it, instantiate each class as the default, encode each object as a plain old dictionary (they all have a 'props' method that returns the object represented as a JSON-suitable dictionary), and JSON-encode the whole mess. It totals like 5 lines for the whole thing, not counting the list of classes to be exposed.
- sah 18y agoYeah, that's exactly what I meant. I sometimes see people create an entire class wrapping a single factory method, and then override that method in various subclasses to construct different types of objects. The class, the subclasses, and the factory methods are all redundant in Python. The Twisted framework is an offender that comes to mind. I haven't worked in Java very much, so I'm not sure what the trade-offs are with using reflection vs. factory methods. But GoF gave examples in C++, and was published in 1994, before the reflection API was released with JDK 1.1 in I think 1997. It's entirely possible that using factory methods to customize the concrete types of objects doesn't make a lot of sense in Java, either.
- marcus 18y agoI once saw code that had factories that generated factories that generated factories. Yuck... Like the ancient world view, "it's turtles all the way down"
- Tichy 18y agoBut think about the generalizations it affords... ;-)
- nuggien 18y agoThere are no stupid design patterns, only stupid programmers who don't understand why they are using the design patterns.
- jauco 18y agoonly stupid programmers the thing is, you can't just read a book about design patterns (any book, no matter how well written) and know when to apply them. You'll have to try it, make mistakes, learn from them, make mistakes in the opposite direction and so forth. People should build some personal throwaway projects and cram in every design pattern they know. That should at least get them started on the learn/mistake cycle. At least it did so for me. Though in my last project I was totally abusing the factory pattern while all the while chanting "I shall not use patterns when they are not necessary" :blush:
- andrewl 18y agoThat's right. The programmer may not be stupid at all. He or she may just be in the middle of learning patterns. One might say that only stupid speakers make simple grammatical errors. Or they might be beginners in a second language. I hope and expect to always be a beginner in something in my life, whether it's a new computer or human language, a new craft, or some other new way of thinking. By the way, Peter Norvig says that in Dylan or Lisp, 16 of 23 patterns are either invisible or simpler. That's from the "Design Patterns in Dylan or Lisp" slide from his Design Patterns presentation at: http://www.norvig.com/design-patterns/ http://www.norvig.com/design-patterns/
- ComputerGuru 18y agoOK, so reading this article is enough to thoroughly convince one to rethink the usage of Singletons. But what other design patterns would you guys recommend? Most of the common design patterns are some form of Singleton implementation or the other and suffer many of the same drawbacks Steve points out in the article - what are the alternatives? (I've been making do with custom interactor classes that perform object sharing by using linked-list of class instances with a custom "mapper" and though it works great it's really hard to explain to anyone). Also - any books you guys would recommend as an alternative to Design Patterns?
- DanielBMarkham 18y agoI never liked the patterns books because I always thought they gave you solutions without knowing what the problem was. Ever learn MVC? Might be a good place to start.
- ComputerGuru 18y agoWhen you write your own MVC you'll come right back to the original patterns question. MVC is just the thing programmers interact with so they don't have to deal with inter-class interactions directly. But the MVC framework itself needs to manage those interactions somehow, using one pattern or the other.
- DanielBMarkham 18y agoSure enough. So your question is "How do I write good controllers?" It's kinda hard for me to give you specific advice without a model and a set of behaviors to traverse. I guess "do good things" and "don't do stupid things" is about it. Singletons are not evil, but, like, gotos, I'd try to avoid them if at all possible. In my experience, once you've matured the model enough for it to be code, you're automatically thinking in terms that leads to good design. Singletons pop out when you start with a small piece of the problem and try to bludgeon whatever you've got into a solution. These problems arise when you start to design from the bottom-up and use functional paradigms instead of OO paradigms. Nothing wrong with that, but for good code you should really pick one or the other and stick with it.
- mojuba 18y agoCuriously, somehow only in OOP there is a real need for teaching/learning "patterns", whereas outside of the everything-is-object world anything you do is a "pattern".
- hobbs 18y agoIndeed, I found that this statement sounded alarms in my critical thinking cortex: "the Singleton "pattern" encourages you to forget everything you know about OO design, since OO is hard, and procedural is easy." Why, oh why, are we encouraging people to use OO 100% of the time, when it's admittedly harder than the alternatives? (I'm looking at you, Java.) Methinks the bandwagon continues to play on, even after two decades...
- pistoriusp 18y agoSomething that Alex Martelli said in one of his talks when I was starting off with Python was something along the lines of: "Ignore OOP!" I had never heard anyone suggest anything like that before, I think some developers think OOP is "the way forward." I spent many months trying to force my mind to think in an OOP manner, now I don't even bother. Occasionally I find a place where it does work, but it's definitely not a magical bullet.
- stcredzero 18y agoI've just noticed that there are two "impedance mismatches" in a lot of applications. UI -> Domain Model -> Persistence Most people know of the 2nd one. The 1st one is just as big an impedance mismatch! Most of the ways of doing UIs are not OO. If UIs were OO in a given environment, then naive developers following the path of least resistance starting from the GUI "hello world" would naturally build an OO application. Are there any environments like that? Is Rails one such environment?
- hobbs 18y agoMost UI code is intrinsically event-based. e.g., "on click, do this", "on resize, do that" Erlang comes to mind as a good event-based language. Strangely, it is rarely (if ever) used for UI.
- bvttf 18y agoPages 243 to 256 are, in my copy at least, the Interpreter pattern, in case anyone else was wondering.
- icky 18y agoI wasn't, but my Observer was...
- andreyf 18y agoPages 243 to 256 are, in my copy at least, the Interpreter pattern http://en.wikipedia.org/wiki/Interpreter_pattern http://en.wikipedia.org/wiki/Interpreter_pattern From what I can tell, using this is a pretty clear sign you should be using a language with macros...
- Hexstream 18y ago"In my Data Structures course in college, when we got to AVL trees, my prof turned and wrote on the board, in huge, clear letters: AVL Trees are EVIL ...and that's all we had to learn about them. He had us implement red/black trees and splay trees instead. To this day, I have no idea how threaded AVL trees work. But if that's OK with Dan Weld, it's OK with me. " Thank goodness it wasn't: "LISP is EVIL". Or replace lisp by anything useful and generally misunderstood.
- ambition 18y agoI think the professor's point is that using red-black trees is a dominant strategy over using AVL trees.
- alex_c 18y agoDo I get bonus points for not really seeing much point to the Singleton pattern when I read the GoF book? In fact, I can generalize that to say that all the patterns seemed either obvious or pointless. I still haven't decided what that means about me as a programmer.
- icky 18y ago> Do I get bonus points for not really seeing much point to the Singleton pattern when I read the GoF book? This comment entitles the bearer to one (1) Hacker News Bonus Point. Don't spend it all in once place.
- deleted 18y ago[deleted]
- shiro 18y agoMy reaction was similar. Later I found they were useful as a communication medium when you worked in a team that were doomed to use Java or C++; walking may be a natural thing for you that wouldn't need an explanation, but knowing that action is called "walking" helps when you explain to someone how you get to somewhere. Of course, if you're using more succinct programming languages, it may be much faster and accurate to write a line or two of the actual code to show what you mean, rather than remembering all those names of the patterns.
- DanHulton 18y agoWhen writing a game, I tend to have a singleton "Game" or "World" class (well, actually a static class, I don't bother with all the getInstance() crap), and from there a bunch of proper classes all "owned" by Game. Now, I'm basically using static classes as a namespace here, but is this really that harmful? If so, what options do I have?
- Tichy 18y agoI guess it will fly in your face once you'll try to create multiplayer games and serve several games at the same time? What do you gain from making a game a singleton?
- DanHulton 18y agoWell in that case, I'd have a Server class and a Client class. One handles logic and the other handles display and input. And actually, for my last little prototype (now that I think about it), I didn't make it a singleton, I just had a single public instance of it. Question retracted.
- ken 18y ago"The problem is, about 1/3 to 1/2 of them were basically cover-ups for deficiencies in C++ that don't exist in other languages. Although I'm not a huge Perl fan anymore, I have to admit the Perl community caught on to this first (or at least funniest). They pointed out that many of these so-called patterns were actually an implementation of Functional Programming in C++." Compare Norvig (1998): "Design Patterns in Dylan or Lisp: 16 of 23 patterns are either invisible or simpler". http://norvig.com/design-patterns/ http://norvig.com/design-patterns/