10 ms·
Design Patterns – A comprehensible guide
- TillE 10y agoI appreciate the effort, but one of my pet peeves with OO / design pattern examples is when they're completely contrived. Once you've understood the very basics of OO, I think talking about a door factory or a burger builder tends to obfuscate real-world usage more than it aids comprehension. I have this problem with most science/technology analogies, to be honest.
- sna1l 10y agoIt would be great if there was a resource with real world examples, since I have this exact same problem.
- jneal 10y agoI'd say when I was first learning about many of the design patterns, this was my biggest hurdle as well. The examples and analogies were unrelated to real-world scenarios and didn't do much to help me understand the concepts. It wasn't until I came up with my own real-world examples that were specific to my domain and really applied the design patterns in practice that I really started to understand everything. I don't think it's really the real-world example that helped so much as the actual process it took to arrive at an implementation.
- macintux 10y agoDisclaimer: I haven't looked at it in many years, but I seem to recall Fowler's Enterprise Patterns[1], while covering a higher layer of abstraction, grounded in real world problems. [1] https://www.martinfowler.com/articles/enterprisePatterns.html https://www.martinfowler.com/articles/enterprisePatterns.htm...
- keithnz 10y agoGrady booch was working on a "handbook of software architecture". What he was doing is go to companies and look at how systems have been built. there's a presentation https://pdfs.semanticscholar.org/242a/61777fd7f0f7ded8d9326e420ebd7e888288.pdf https://pdfs.semanticscholar.org/242a/61777fd7f0f7ded8d9326e... He was looking at the structure, and the patterns in real world systems
- rezashirazian 10y agoI implemented some of the more popular design patterns using more real life like examples. You might find them useful : https://shirazian.wordpress.com/2016/04/11/design-patterns-in-swift/ https://shirazian.wordpress.com/2016/04/11/design-patterns-i...
- callumprentice 10y agoReminds me of physics books from college where they might say "a horse is approaching a barn door at relativist speeds..." - always seemed much too contrived and I'd maybe have preferred "an exotic particle is moving towards an electron at...".
- danielbarla 10y agoI know I might be in the minority, but this kind of stuff doesn't bother me at all. The silly abstraction is essentially there to highlight which part of the problem / lesson you should be focusing on, and to stop you from going off on a tangent and getting bogged down in the gritty details. Going with your exotic particle example, once they've framed the problem like that, there's an implied expectation of reality and correctness which is likely going to be missing from an introductory example.
- Sir_Cmpwn 10y agoThe physical behavior of a horse is better understood than that of an electron and might make it easier to consider the subject at hand, though. We know what path the horse will travel and we know that when the horse reaches the barn, it will go splat (well, in this case the barn will go splat). There are several competing theories that could describe what happens with the electron and the exotic particle, though. Also, it's fun to picture a horse travelling at relatavistic speeds :)
- Jugurtha 10y agoCheck out Soviet books. You don't get the feeling the authors assume you're mentally challenged as you do in most other books. This is all fun, but I think knowing how to apply knowledge is an important part. Many don't have a problem with electrons and pulleys, but put a real world example and they're out of their wits compared to someone who uses to dead reckoning. https://mirtitles.org/ https://mirtitles.org/ There's an interesting book on the site by Belikov: "General Methods for Solving Physics Problems".
- joe_the_user 10y agoIt's not so much they're contrived but that starting with real world, physical examples is ultimately not helpful. OO objects are not physical objects and the sooner someone realizes this, the better.
- hackits 10y agoQuestions like “Which paradigm is better for modeling the real world” are virtually meaningless. The choice depends upon how the world is conceptualized, and what additional properties are expected of the model.
- rezashirazian 10y agoA while ago, as an exercise I decided to implement some of the more popular design patterns in Swift, using more real life like examples. If you're interested you can find it here: https://shirazian.wordpress.com/2016/04/11/design-patterns-in-swift/ https://shirazian.wordpress.com/2016/04/11/design-patterns-i...
- JamesBarney 10y agoRight, stop making pained carpentry analogies. I couldn't build a wooden box to save my life, but I do have 7 years of professional software experience. I would much prefer if you drew from that experience.
- Traubenfuchs 10y agoBe careful what you wish for. We can always take the "zoo animals with varying legs" classes and interfaces out of the box again.
- morbidhawk 10y agoIn addition to contrived examples impairing comprehension I even think a real-world example fails to help the reader capture the most important piece of information about design patterns, and that's the context around when to use them. Giving a worked-out example while teaching the concept has the limitation that the reader didn't discover the pattern themselves in code, instead it was ripped out of a code base and handed to them without context of its use. And instead of seeing it as an option that was selected to be used in a particular code scenario it is instead presented as a fully-worked solution that can be plugged in anywhere and describing when to use it in words isn't as effective as discovering it being used in a code base you've been learning from. Quite frankly, in my radical opinion, I think learning about programming through reading about it (books, articles, blog posts, etc) isn't very useful once you are past being a beginning programmer. To be a better programmer reading code is the only way I've seen good progress with learning new abilities that don't cause me to over-engineer my own solutions. This might not work for everyone but for me reading code daily has been a silver bullet to programming knowledge that a book or design pattern article could never capture for me.
- ilugaslifg 10y agoObject-oriented programming is a disease, and I can't wait until we're collectively done with it. All of these abstractions, when rarely they are actually needed to express a program, can be naturally expressed within the type system, in a proper functional language. The fact that there's this encyclopedia of hundreds of discrete things with arcane toxic names that practitioners are required to individually learn and carry around in their heads, is a crime against our profession.
- dang 10y agoThis sort of heated rant makes for a bad HN comment, regardless of how correct your views are. It leads to flamewars, which we don't want here, so please don't post like this. Even if you took out the rantiness, the comment is still too generic to actually be saying anything. So to convert it to a good HN comment, you would need to both de-flamebait it and add information (e.g. specific examples).
- catshirt 10y agoi enjoyed the conviction.
- revscat 10y agoThere is far too much conviction in the world. One of the reasons HN is so enjoyable is that the discussions tend to avoid the heat that you can find just about anywhere else.
- iak8god 10y ago> There is far too much conviction in the world. Are you sure? :)
- dang 10y agoI can appreciate that, but empirically we know from long experience that such comments lead to downward spirals. That's why the site guidelines are the way they are; it isn't to dampen conviction.
- wenbert 10y agoThanks for this. And I just realised, examples are in PHP!
- swsieber 10y agoI think the reason that some of these patterns seem so terrible in real code is limited static type systems / OO - I'm specifically looking at Java, and it's terrible type erasure, and poor (but getting better) functional programming support.
- ktRolster 10y agoThe reason I like Lisp is because programming in it teaches you how to organize your code well using the most basic and important design pattern: the function.
- krapp 10y agoYou can implement design patterns with functions, but functions themselves are not a design pattern.
- icebraining 10y agoWhy not? They are general repeatable solution to a commonly occurring problem in software design - ie, a design pattern. You had non-structured code, then people started using small chunks of code that you'd jump to and back from multiple locations. It's a pattern, that just happened to get encoded directly into some languages, just like others (Norvig talks about the levels of implementation in his presentation on the subject: http://www.norvig.com/design-patterns/design-patterns.pdf http://www.norvig.com/design-patterns/design-patterns.pdf)
- krapp 10y agoTo me, functions alone aren't abstract enough to be considered a design pattern. If they were, any arbitrary chunk of code, however disorganized, could be considered an implementation of that pattern as long as it used functions, which seems counter intuitive.
- ktRolster 10y agoThere are good ways and bad ways to use functions, just like any design pattern.
- monocasa 10y agoI think they're just a victim of their own success. Particularly the iterative language concept of 'function' is by no means universal. They were kind of grafted onto mainframe architectures, and even the MIX from the original The Art of Computer Programming used self modifying code to perform subroutine calls. Functions are an extremely common pattern more or less expected by every language, but I'd definitely call them patterns still.
- opk 10y agoThe main value of the design patterns is that they have given names to things that were already common and fairly intuitive to a half decent programmer. But I've come across many people trying to use them as a guide for how to write code - and misunderstanding them. Factory in particular is often misunderstood. It is mainly useful when you have parallel class hierarchies not as some odd wrapper around all the constructors in the software.
- yoodenvranx 10y agoThe one you mean is called "Factory Method Pattern" in the Gang of Four book. The other one should be called "Simple Factory" or something like that. They are very different things which unfortunately have very similar names.
- opk 10y agoI don't really see what you call a "Simple Factory" as being covered in the Gang of four book. I should have been clear about meaning Factory Method but the terminology is often apparent in class naming. So for the "Abstract Factory" pattern, I would use "Kit" in class naming. I would reserve "Factory" for the "Factory Method" pattern. Pointlessly wrapping constructors in a separate class and calling it a factory doesn't really get you anything. Neither does contriving a parallel hierarchy to pointlessly allow the use of the "Factory Method" pattern - something that I have also seen.
- dack 10y agoI'm not sure what you mean by parallel class hierarchies. I use a factory if I have a class that needs to be able to make an instance of some other class, but shouldn't know about how to construct it (i.e. it doesn't need to know about the dependencies that other class might need to function).
- mikekchar 10y agoI shouldn't speak for the OP, but I think they are referring to the fact that the factory pattern very naturally shows up when you also have the bridge pattern. You have 2 (or more) parallel class hierarchies and you need a way to construct the objects from the correct hierarchy. You are also correct that it happens in other places too. Some people overuse it, though. They abstract out the construction of their objects for no reason at all. You already have a constructor -- usually there no need to have an object that contains all the constructors.
- alashley 10y agoI wish there was a resource that goes over design patterns with more abstract concepts/classes. I found the example in GoF to be somewhat useful but at a certain point (near the middle) I got lost in the details.
- dack 10y agoYou want more abstract examples? Or more abstract patterns?
- alashley 10y agoMore abstract examples.
- asitdhal 10y agoThat's why GoF book is available in the library. People write more concrete tutorials and publish online. Abstract literature is for researchers and Concrete literature is for people who need a quick solution.
- 0x54MUR41 10y agoIn my opinion, iluwatar's design pattern guide [1] provides more examples than this. It gives not only implementation examples but also a class diagram and use case for each design pattern. The examples were implemented in Java. [1]: https://github.com/iluwatar/java-design-patterns https://github.com/iluwatar/java-design-patterns
- coleifer 10y agoStop the for humans meme. Try-hards use it to signal that they're "in" but its outlived any meaning beyond some meta-meaning which is no meaning at all. Just make your project quality. Don't proclaim it, just do it.
- LyndsySimon 10y agoNote: this comment should not apply to Kenneth Reitz.
- brockvond 10y agowhy on github and not on like... medium?
- LyndsySimon 10y agoOff the top of my head: 1. GitHub is a broadly-adopted tool that the author probably already knew how to use 2. It's hard to accept PRs on Medium 3. It allows the author to list the repository on his profile, thereby helping them convey competency to potential employers 4. It's easier to archive a git repo than a Medium post, and easier to rehost elsewhere in the future if/when GitHub dies. 5. Git allows change tracking. 6. It uses Markdown, which can be processed through automated tools to produce a variety of formats, from PDFs for email to EPUB to send to a physical publisher.
- brockvond 10y agolol - that's a good list. thank you.
- js8 10y agoIn a galaxy far far away, there was a kingdom where people didn't know structured programming. Their programming languages only had (conditial) branches, jumps, or GOTOs (as they were colloquially called). And they had a very influential programming book, called "GOTO design patterns". Here's a few examples of design patterns from the book: - "IF pattern" - If you need to execute code only if some condition is true, you write a conditional GOTO that lands after the code that is to be executed conditionally. - "IF-ELSE pattern" - If you need to execute code only if some condition is true, and some other code if the condition is false, you use IF-ELSE pattern. It's similar to IF pattern, but at the end of the code in the IF pattern, you add another unconditional GOTO that branches after the code that is to be executed if the condition is false. - "WHILE pattern" - If you need to repeatedly execute code and check some condition after each execution, you add a conditional GOTO at the end of the code that goes back to the beginning of the code you want to repeatedly execute. - "BREAK pattern" - This is a pattern to use with the WHILE or UNTIL patterns. If you need to, on some condition, stop repeated execution of the code in the middle of the code, you add a conditional GOTO into the middle of the code that just branches after the repeatedly executed code block. Everyone was happy with the book. No more messy spaghetti code full of random GOTOs (as was common before the book appeared), because young apprentices memorized all the patterns in the book, and they just applied them rigorously. Also, understanding code became easier, because everybody instantly recognized those patterns in the well written code, and they had a common vocabulary to talk about these things. One day, a traveler from another world came into this kingdom. He looked at the book and wondered: "Why don't you just add these patterns into your computer language as abstractions? Wouldn't that aid comprehension even more?" Unfortunately, he was executed for the heresy.
- thom 10y agoThis is, and always has been, a poor criticism of design patterns, by people who think they're just a library of code that idiots are supposed to cut and paste to be better programmers. A common example from the GoF book is the Strategy pattern - most functional programming snarks will jump in and say you don't need this! We have first class functions you can pass around! And it's entirely true that an implementation of this pattern (a good, simple one even) is just accepting functions as arguments - cool, you probably get it! But the _design_ principle is about making strategies _explicit_ - allowing decisions to be made or policies to be enforced in ways you don't anticipate. I still see _tons_ of libraries written by smart people in functional languages that will still accept an enum of some kind to tell them what do in certain situations (e.g. a lot of HTTP libraries' extremely limited retry logic). That's an explicit design decision - to limit options instead of opening them up. Having a language to talk about the _design decisions_ at a higher level, instead of conflating them with language features, is the whole point. Everybody knows you can pass functions around as arguments, that doesn't necessarily prompt you or make it easier to discuss implementing a Strategy. Design patterns aren't a static, finite set of code snippets, and I actually think things like the linked post that mostly treat them that way aren't helpful. They give you a way of naming and talking about components of a design, possibly at a higher granularity than your programming language (and sure, different languages have different granularities). We've been hearing this same exact criticism for literally 20 years and it's boring at this point. I get that most people don't bother creating new design patterns in public these days (because they've internalised that modern languages have 'design patterns' built in), but if you look at something like React and think it's just JavaScript and there are no design decisions in there worthy of reifying, I think that's sad and unproductive.
- prefect42 10y agoOne can argue these topics until the cows come home, and possibly later. One can strongly argue for/against imperative programming, functional programming, OOP, design patterns, Design Patterns with Cool Names, Design Patterns as Implemented in Your Favorite Language, etc... At the end of the day, the only thing that matters is whether your team thinks your source code is structured or not. If you're on a team of one, well then you have your future self to contend with.