A pattern a day keeps the reviewers away (7 Part Series)
During the past few months, I've been working on a back-end project made with Ruby on Rails. Last year I was working as a Front-End developer, I've never had the opportunity to apply design patterns almost anywhere, until now.
It's a pretty useful thing, that probably every developer that works with objects should at least know and practice, and this is why I'm here, to give you (and me!) a daily short post about the different design patterns that exist (or at least, those that are used the most), with an example, and an explanation.
Because doing good code will help you, your workmates, and those who will be in the future.
Today, I'm writing about a really famous pattern you may already have heard about. It is called the Service Object Pattern.
The cover image is pretty much self-explanatory. A service object (also called services) is a simple and powerful pattern, easy to test and with a wide area of use.
It will help you to decompose your fat models and also to keep your controllers slim and readable. Sounds cool, isn't it?
To generate a service object, you have to create a new class. Inside this new class, you have to try as better as you can to have one public method, and to keep a single responsibility for the object.
Let me explain the example before you read it. We are creating a class to manage all the logic for an event dashboard. Before, we called all our order methods directly in a part in the controller where we generated our event dashboard. To make this looks cleaner, I've decided to extract all the logic into the succeeding class:
Things you need to have in mind:
- Try REALLY hard only to have one public method.
- Managing Dependencies can be hard. Do it privately and optimally.
- Return something meaningful. An object.
Now, in our controller, we can initialize the object and call it, making both the order logic and the dashboard initialization easier to read, just like this:
Now, it looks cooler ✨
And this is my first (actually second but shh, first pattern) article about design patterns for the series "A pattern a day keeps the reviewers away".
You can read the previous article here:
BTW, I'm going to show the examples mainly in Ruby, which is, in my opinion, one of the easiest one to read and understand. This does not mean that this design is not applicable to your prefered language.
I'll try to keep posting every day one of the different patterns that are around. I can't promise I'll fulfil this task every day though!
You can read more about this pattern at:
Also, you can follow me so you are tuned to whenever I post something through my Twitter account!