DEV Community

Discussion on: Business logic in Rails with operators

Collapse
citronak profile image
Petr Hlavicka Author

Thanks for the feedback. The reason is, that I don't want to have the business logic inside the model. I want to have models as a place for things mostly related to the database (like validations and associations and so).

Models with business logic inside have too many responsibilities.

Collapse
choltz profile image
Chris Holtz

I completely agree.

In smaller rails applications, one can probably get away with mixing models with business logic, but after a certain size, it becomes a tangled mess.

Separation of concerns is important. If models are dedicated to query and data storage, and operator classes are dedicated to business logic (and presentation logic is in helper/decorator classes and configuration logic is in initializer classes, etc.), then you know exactly where to look for different types of code.

Further, pulling business logic into a PORO opens opportunities for much faster test runs, since the test suite can bypass the DB altogether for some business tests. Similarly, the operator objects in your article, for instance, allow allow one to run tests on code that would otherwise have required the slow overhead of a controller test.

While the database (and therefore model) structures inform the business operations, one does not need to dogmatically adhere to that structure in the business layer. This is particularly the case when your app also relies of data sources beyond the database or when you have multiple apps that need to read information from the same database.

Thread Thread
jaredcwhite profile image
Jared White

"If models are dedicated to query and data storage"

"While the database (and therefore model)"

Again, I fear we are treading into dangerous waters of conflating the model layer of an application with the ActiveRecord pattern specifically. You can have a wide variety of objects employing all kinds of different patterns and many of them will of course be POROs. Only some—perhaps only a few even!—of the objects in app/models need be literal ActiveRecord objects. ActiveRecord is just one pattern among numerous potential avenues of exploration in OOP.

Collapse
jaredcwhite profile image
Jared White

Everyone's entitled to their architecture, but I believe models are precisely where you do want business logic. Jason Swett and I go into this in-depth on his podcast: codewithjason.com/code-with-jason-...

It's talking about service objects more particularly and why we don't care for them, but it's thinking to apply here as well. You can obviously create either concerns or POROs inside app/models, and in turn utilize those from within your ActiveRecord models. But in my opinion using AR models themselves as the primary API for your domain layer whenever possible is a winning strategy.

Thread Thread
citronak profile image
Petr Hlavicka Author

Thanks, Jared, I will definitely listen the podcast.