268 points · by kamranahmed_se · 9y ago · 110 comments
- "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.
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.
Anyway, I think we have an ontological disagreement here. I don't believe the "design patterns" which cannot be formally defined are useful, or even that they exist. I consider them to be just phantoms, which when you attempt to formally define them, you either understand them much better (to the point where you can see how they are related), or they disappear as something that was misconceived in the first place. You seem to think that there is something real.. fine.
Possibly, why I see it that way is my mathematical training. In mathematics, this battle was fought more than a century ago and the formalism camp won. That doesn't mean that intuition is completely useless.. just that people mostly keep their intuitions (and inspirations and analogies) for themselves, and when they communicate, they strive to be formal.
To your React example - it's not a pattern, it's a piece of concrete reusable code. We don't need "React pattern", but we need React. Just like mathematicians, we should communicate "patterns" via reusable code.
And I'm not saying React itself is a pattern. I'm saying if you wanted to create your own React-like framework, or to communicate the design decisions and mechanisms that make it different from other frameworks, there is value in extracting and naming those concepts. This way, people can appreciate, understand, compare and contrast them _outside_ the context of one piece of concrete reusable code. As an entirely throwaway and unthought-out example, you might say 'Differential Rendering' is philosophically different to a 'Mutable Document'.
But if you think all things in the design of software are reducable to reusable pieces of code, more power to you.
The result of the urge of explicitly abstract every pattern can end up being a brittle network of dependencies. It can become really hard to adapt the formal abstractions to small requirement changes—either that or the abstractions end up byzantinely parameterized.
Or you have to spend decades doing category theoretical research to discover the platonic essence of your patterns...
Formalization hasn't really won in math communication, has it? How much math researched is published as Coq terms or whatever? Maintaining all of math as a network of formal abstractions is really difficult.
Basically the insistence on maximal abstraction seems to imply that you try to minimize the length of application source code and as a side effect you maximize the complexity of programming languages and frameworks.
By the way, Richard Gabriel discusses this issue in a chapter of his book "Patterns of Software" (free PDF available).
I often asked myself this question! Why do I have to say
public class DatabaseConnectionSingleton {
public static DatabaseConnectionSingleton getInstance (){ ... };
}
and then get an object using: var db = DatabaseConnectionSingleton.getInstance();
Why can't I say public singleton DatabaseConnection {...}
and just go var db = new DatabaseConnection();
and let my runtime make sure that I get the appropriate instance? Left aside the discussion of how useful that pattern is, I would like my language to be more powerful. I am aware of alternatives (Borgs in Python) and that many people consider Singletons an antipattern, as it helps introduce globally shared state, etc. but then, why do I have to care about how instances are implemented?After all, in C#, foreach interacts with iterators, why not push other mechanisms down into the language in the same way?
Ideas:
// Unit of work, commits changes before the reference gets removed from stack
public unit CustomerForm { }
// There can be only one.
public singleton DatabaseConnectionHighlander {}
// Any method called updates values in some way
public builder QueryString {}// There is only one object DatabaseConnectionConnor {}
I found that it often helps to remember that the GoF book was written about object oriented patterns with C++.
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.
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.
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.
There's an interesting book on the site by Belikov: "General Methods for Solving Physics Problems".
Also, it's fun to picture a horse travelling at relatavistic speeds :)
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.
https://shirazian.wordpress.com/2016/04/11/design-patterns-i...
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.
there's a presentation https://pdfs.semanticscholar.org/242a/61777fd7f0f7ded8d9326e...
He was looking at the structure, and the patterns in real world systems
[1] https://www.martinfowler.com/articles/enterprisePatterns.htm...
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.
The value of design patterns and giving them appropriate name is to have a common language, a basis for communication. Sharing ideas or giving instructions is much simpler when you can actually name something with a few words.
Here is another use case for a factory: Building an AST data structure in a compiler. There are nodes to represent Constants, Addition, FunctionCalls, etc and you have to build a tree structure, which represents a program.
Now consider the case, where you build the addition of two constants ("36 + 6"). Using constructors, it could like like: new Add(new Const("36"), new Const("6"));
Using a factory: f.newAdd(f.newConst("36"), f.newConst("6"))
The advantage of the factory is that it can optimize on the fly and return a Const("42") node instead of an Add.
I remember that at some point gcc -O 0 was doing exactly that and it is pretty irritating if you write a decompiler and want to test it. Fortunately clang does it properly.
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.
They are very different things which unfortunately have very similar names.
Functions are too simple and concrete to be patterns. A function is a mapping from one set to another. Even category theory manages to fully generalize functions several different ways without managing to define something as general as a pattern.
So, you might ask, what are patterns? Patterns are things which repeat somehow. That's it. There might be more to it, but I have yet to find it.
I'm glad that you like Lisp, but it's not the beginning nor the end of programming. For example, the Post correspondence problem is Turing-complete. So are Wang tiles. Where's your functions now?
Abstration can take many forms. But can often be described as "seperating things that change and/or repeat from those that don't", or something like that.
The last paragraph may be a joke, or based on one of the Principles in the O'Reilly Design Patterns [2] book.
[1] https://mitpress.mit.edu/sicp/ [2] http://shop.oreilly.com/product/mobile/9780596007126.do
If using GOTO in Windows batch files counts, then I kind of have.
>Figuring out how to use functions appropriately is one of the most important skills of software engineering.
Yes, but that's not so much a design pattern as discipline. Knowing what patterns to use and when.
People write more concrete tutorials and publish online. Abstract literature is for researchers and Concrete literature is for people who need a quick solution.
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.
If you think FP is mutually exclusive with OOP, you understand neither.
OOP is very powerful to organize the architecture of your code and capture very common patterns such as reusing an existing piece of five functionalities while overriding one (something that's still awful to achieve in FP, regardless of the language you pick).
FP operates at a more granular level, basically how you implement your methods.
And by the way, FP has design patterns as well.
FP and OOP are extremely complementary.
This is not true, ad hoc polymorphism works fine without subtype polymorphism.
Show me an example of a type class with five functions and then how I can reuse it while overriding one of these five.
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).
All that said, there is a place for OOP. And while a world without OOP would be a better place than a world without FP (if we had to choose), I think you'll be waiting a looong time for that world to materialize.
The mental fun was when it dawned on me that most of the benefit from the FP I was falling in love with was coming not from FP itself, but from the liberal use of immutability... and that OOP can be written in a way that similarly embraces immutability.
I don't know if my OO code got better or worse from an outside perspective once I realized that, but it certainly made it easier for me to reason about my experimental side projects.
Oh come on. It's not "arcane" and I don't see how "toxic" has anything to do with the names of these patterns.
Just an inflammatory comment.
The other main concern was it was over-hyped with consultants running around to all businesses during the dot net time with xml with no empirical evidence to backup their claims.
The whole OOP was a giant experiment.
I'm not dishing OOP per say. My main concern is OOP emphasis (Java) is everything needs to be a class. There are times when there isn't a need for a noun for a bunch of functions that operate over a collection of abstract data types. The other problem is how OOP is first introduced to programmers. They're taught they need to categorizing everything into a taxonomy (classes) and inheritance. So the emphasis is incorrectly put on the art of taxonomy instead of getting the job done the most straight forward approach.
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.