Single responsibility principle with Services Objects/PORO in Ruby

Single responsibility principle with Services Objects/PORO in Ruby

Everybody know that importance of organization own code to provide scalable functionalities, about the MVC partner, some developers already implements ungly code in wrong place, like a domain logical in controller or the worst, in the view to delivery the project quickly, i presume that a lot of developers do that, include myself too, in the past, of course :) (never do that Yonatha!).

In Java or PHP, I loved create a business layer to separate the behavior of domain logic and in Ruby, it’s not different, but called PORO or Services Object.

In this article, I'll introduce the principle of SOLID design principles: Single responsibility Principle (SRP).

Note: All you need know about SRP:

  • A class should only do one thing
  • A class should have one reason to change

Don’t confuse de Service class with service or microservice architecture used in docker or some like that

What’s benefit of create a Business/Service layer?

  • Unit test 
  • Clean code
  • Skinny classes
  • Identify responsabilities
I learned to make fat Model and skinny Controller, it’s wrong?

Yes! Because in the MVC partner, Model represents the entity of database and in Ruby On Rails for example, do you can create validations of attributes before persist data, like a validation email or if a integer, uniq, length, it’s presence.. All rubyist know about that, but, if you need implements business logic?

Save the world! Let’s suppose you have a Payment model with relationship (has_many) with Product, and you should calculate amount of payment (calculateAmount), your implementation seems like this:

No alt text provided for this image

Looks good for some devs, but here, we have business logic inside our Payment model, instead of, we can move this method in new class called Payment Service to separate responsibilities of classes and effective isolation to Unit Tests.

For that, we can create a below code:

No alt text provided for this image

Concentrating the core logic of the application in a separate object

No alt text provided for this image

To use Services Object approach, we can just keep this three simple word in our mind: input, perform and return the result, without any bullshit of alchemist programmers.

Anyway, I hope that this little article help you. In the next post, I’ll write about the O (Open/closed principle) of the SOLID principles.

Cheers

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics