Re:Ways to Decompose Fat ActiveRecord Models
by ollysb on Wednesday October 17, 2012 @11:11AM
(#4664767)
I try to follow a gradual approach to decomposition. When I start to get a lot of related methods I wrap them in a module, but still within the model definition(I just include the module immediately after definition). From there I might just move it to a separate file as is or perhaps I turn into a decorator and add an accessor for it on the model e.g.
class Retailer
...
def metrics
RetailerMatrics.new(self)
end
end
class RetailerMetrics < Struct.new(:retailer)
def profit
# devious stat twisting
end
end
The biggest danger with any of the patterns from the article is that you start using them before you actually need them. Then you just end up with a lot of complexity for no benefit.
Re:Ways to Decompose Fat ActiveRecord Models
by brynary on Wednesday October 17, 2012 @11:16AM
(#4664792)
Yes! Gradual is they key. Your architecture should scale up gradually to handle the app complexity.
Re:Ways to Decompose Fat ActiveRecord Models
by tmorton on Wednesday October 17, 2012 @11:05AM
(#4664739)
I don't have any research, just a rule of thumb: refactor when it hurts. In my experience, it's easy to go too far in the other direction, trying to craft perfectly generic code on the first pass. That doesn't work very well.
It's important to have a meta-awareness while programming - how firm is your grasp on the code? How confident are you that your changes will do what you expect? At some point, you feel that grasp slipping, and then it's time to refactor.
Re:Ways to Decompose Fat ActiveRecord Models
by brynary on Wednesday October 17, 2012 @11:08AM
(#4664755)
That's a great summary. It's easy to lose that meta-awareness, even if you're an experienced coder. You are holding a hammer, and the nail isn't going in, so your first instinct it "hammer harder". But usually it means you need a screwdriver.
When doing a small, limited-use project, it seems often that trying to follow "best practices" like avoiding fat models would be more trouble than it's worth. And yet I've worked on larger enterprise-scale projects that have most certainly benefited from following this and other practices.
Anyone know of any research or work on where the tipping point is for following increasingly complicated patterns and practices?