DEV Community

Discussion on: Explain Design Patterns Like I'm Five

Collapse
 
nestedsoftware profile image
Nested Software • Edited

Hmmm, it's bit tough to come up with a truly eli5 example for this, but I think the basic idea is reasonably simple: A design pattern is a structure of code that you can apply to many different problems.

I don't think it's generally thought of that way, but to me, even something as simple as a humble for loop is a kind of design pattern. It's used to loop over some kind of iterable and then inside the loop you execute some piece of logic. The for loop is a re-usable structure of code: It can be used for all kinds of different applications. Therefore it's a simple design pattern!

In the 90s, a book called Design Patterns, Elements of Reusable Object-Oriented Software was published. This book became quite influential in the object-oriented programming community. In this book, each pattern is basically a piece of boilerplate code that can be used to reduce duplication and increase flexibility when solving a type of problem. You can think of this pattern code as a kind of harness or scaffolding: You start with this pattern code and then you fill in the actual logic for your specific situation. The Design Patterns book has ideas that are quite common in programming today. For example it describes the proxy/decorator pattern that's used quite a bit in many contexts these days.

Often when someone refers to design patterns, they're either talking specifically about one of the patterns in this book, or they could be talking about patterns that other authors defined later on. For example in 2002, Martin Fowler published another influential book of design patterns around enterprise programming called Patterns of Enterprise Application Architecture. Among other things, this book spends quite a bit of time on design patterns for mapping an object-oriented application to a relational database. You can see some of these patterns mentioned specifically in some ORMs (object-relational mappers), like active record in the Rails framework, or data mapper in SQLAlchemy. That means design patterns can also be useful as a shorthand for communication among developers.

On the negative side, design patterns can become a temptation to over-design one's code, so that's always something to keep in mind. The basic trade-off of design patterns is that they generally give you more flexibility at the cost of increasing the level of abstraction/indirection. It's like anything else: Having a tool in your toolbox is always a good thing, but it doesn't mean you have to apply that tool to every problem you encounter.