Method to Value Object in ActiveRecord Models
Following the Skinny Controllers Fat models approach could lead to reusability problems.
The problem is the lack of separation of concerns. ActiveRecord objects mix behavior unrelated to the core idea behind an ORM¹, which is the abstraction of a database table.
The increase in dependencies for these types of objects makes them hard to reuse in a different context.
My current approach to dealing with unrelated persistence logic in models is by extracting Value Objects².
Identifying concepts in a system might be tricky at the code level, yet, a technique that I have been using recently is to separate data from behavior.
The heuristic leads to the identification of the Explicit model³ of the application.
Sometimes there’s no need to extract a value. It often happens when the definition of the method is talking only about persistence.
Another hint that suggests not extracting this logic is that if I ever decide to test it, I will have to create a record in the database.
What about all the indirection introduced by these Value Objects? My answer is that I prefer indirection over high coupling.
Indirection introduces a boundary between infrastructure details and business logic.
Such boundary separates components that change at different rates, thus making the overall code-base more straightforward.
— — — — -
[1]: ORM: Object Relational Mapper
[2]: Value Objects: Objects that are equal due to the value of their properties.
[3]: Explicit Domain: Define actors, aggregates, and entities representing the business domain. DDD Today — Modeling Uncertainty • Vaughn Vernon • GOTO 2017 (https://youtube.com/watch?v=8Y-XPlXOWoA)