The Law of Demeter

2020-03-06 06:30发布

I recently posted a question on stackoverflow where I did something to effect of

@period_registration.period.event

However, it was suggested that I do something like the following:

def event
  period.event
end

@period_registration.event

My general sense is that this seems a little heavy-handed. Looking at this previous posting How do I apply the Law of Demeter to this? shows how heavy handed this can become if you did this for every association.

How common of a practice is this in rails? My thought is that even if this is technically the right thing to do, if it isn't a part of the rails culture then it seems that doing this will throw people off. And, more importantly, actually make the code less maintainable as other developers think you're wasting your time with all these helper methods.

Let's say I wanted to impliment this, would @period_registration.event.city, where city is an attribute of event, not a seperate object also violate LoD or would I need to write ANOTHER method so I could do: @period_registration.city

1条回答
女痞
2楼-- · 2020-03-06 07:12

To be honest, slavish adherence to the Law of Demeter is pretty rare. Still, for associations, this is such a common pattern that it has a shortcut that removes most of the hard work from you:

class PeriodRegistration < ActiveRecord::Base
  belongs_to :period
  delegate :event, :to => :period
end

PeriodRegistration.new.event # calls PeriodRegistration.new.period.event

You can read more about this at the Module#delegate documentation.

At the risk of sounding excessively self-promoting, I have a blog post that discusses this and other ways to try to respect the Law of Demeter, if that's your thing. Check it out if you're curious to learn more.

查看更多
登录 后发表回答