28th
ActiveRecord != Domain Model
This post is my view on using ActiveRecord classes as domain classes. I have been using rails for quite sometime and have seen this pattern of creating a class and extending it from ActiveRecord::Base every time we think we need a domain class. I am not really comfortable in doing this and following are the reasons why
- I want my domain logic to be free of persistence stuff. Even though ActiveRecord hides it down the inheritance chain the domain class still gets this capability. I want my domain classes to be clean of this and only concentrate on domain logic.
- I think in seperating responsibilities of domain logic and presistance data mapper patterns is a better choice than ActiveRecord.
- I think the domain layer should care only about the domain rules and shouldn’t care how I do my persistence.
- Testing your model seperate is pain as ActiveRecord expects a table of the same name as class name else will throw an error. There are ways to by pass this by meta programming magic but why do we need to do it.
The problem I see with ActiveRecord in rails is it literally creates these classes and puts them in a model folder. The model generator as well hiding most of the stuff behind inheritance hierarchy also doesn’t help much in highlighting this fact to the developer.
I feel that for complex domains it is necessary to have a clear separation between what my domain rules and workings are from how I am persisting.
I may go for the ActiveRecord class being a part of domain layer when my domain is really anemic and has very less rules other than CRUD stuff. What are your thoughts on this.
Keep the model clean of the infrastructure code. It helps in a long run.