Yet another argument with a friend of mine. Consider this code:
class User < ActiveRecord::Base has_many :groups def in_group?(group) groups.include?(group) end end class Group < ActiveRecord::Base has_many :members def add_user(user) members << user end end
My opinion is that these methods add extra unnecessary complexity to the code and are hardly guessable — like why #in_group? but not #is_a_member_of?, or why #add_user but not #add_member, and so on. Coming from my 4 years experience with Rails and total 20 yrs programming experience, I’d better follow AR semantics and use User#groups.include?(group) and Group#members << user. They are easily guessable and in case if I’ll need some extra functionality, I can use callbacks for has_many :members and override User#groups.include? in the association extension module if that would be necessary.
However friend of mine argues that it is better to use shortcuts to creates ‘points of abstractions’ and it is better to extend this code rather than using callbacks or overloads.
What do YOU think?
P.S. just to be clear, I hate ‘WHAT IF’ approach 🙂
I totally agree that these methods should not be added. It’s not the job of models to create other related objects. That’s the job of the association proxy. I’d also beware of overriding association proxy behaviors, since you’re liable to see some strange side effects due to the way the proxies are implemented.