Let's face it - software development is hard. It is hard to show your intent in code, sometimes it is hard to wrap your head around the problem and it is hard to write clean and testable code. In this article Ill try to explain how these problems can be solved by using patterns.
Reason 1 - Common vocabulary
One of the biggest reasons behind patters is communication. When a seasoned developer sees something like a PostPresenter, he can immediately assume that it will tie representation of our data model to view logic. On our projects we use Form Object pattern where we need to put a communication hub between our data model and user interaction. This is the place for validations and specific business rules of user interaction. Showing clear intent is the reason to go for patterns.
Reason 2 - Patterns are accumulations of experience
When we are faced with a complex problem, we need to think about a ton of moving parts. Do my classes comply with SOLID principles? Will this code be flexible enough for me to modify it? Will it be testable? There is no golden answer, but the chances are - someone already solved this problem before you and I can guarantee that 99.9% of the problems have been solved. You just need to search for solution that is expressed in a pattern. Do you have a lot of interactions with third party services and they all have different interfaces? Great - Use adapter pattern. Do you need to hide complex (maybe legacy) system with simple API? Use facade pattern. Stand on the shoulders of giants and don't try to figure it out on your own.
Reason 3 - Better testability
TDD takes discipline and it sometimes can become overwhelming. One of the greatest advantages patterns bring to the table is layering of your code. With good layering we have additional benefit of testability. Across a ton of frameworks like Rails, ASP.NET MVC, Spring there is heavy usage of patterns that already have been implemented for us, but there comes a time when you can't decide where to put your, business specific, code. You can try to work with standard mechanisms that these frameworks offer, but you have to face the challenge of bringing all the baggage of a framework to do your testing. Again, check some of the patterns and see how they can help you to write your layered and easly testable code.
Y'all shall be warned
There is no silver bullet, I've seen pattern names misused and abused in all sorts of ways. You have to think about them intelligently and, before you call certain part of your code Mapper, Presenter, Repository, go reread the pattern description, which will help.
Subscribe to Janis Miezitis personal blog
Get the latest posts delivered right to your inbox