Is it appropriate to repeat data in models to satisfy using law of demeter in collections?

StackOverflow https://stackoverflow.com/questions/6404354

  •  29-10-2019
  •  | 
  •  

سؤال

This is a contrived example, say I want to list the population of a country that a person has a friend in, here are two setups below. Would it be best to repeat data in the models?

I've been told that the Law of Demeter is important to follow, the example is you tell a dog to walk, it is folly to command his legs to walk.

In my wealth of inexperience (noob) I have found that the query would be much easier to do when the models repeat data, People.where(:country => friend.country), vs collections where there are chained associations (which have been impossible thus far): People.where(:city => { :county => { :region => { :country => friend.city.county.region.country }}}) (It would really help this noob here understand the concept if you could imagine the correct contrived LoD setup and syntax, I really hope I didn't use an example that has nothing to do with the Law of Demeter) I've tried applying LoD via delegate and was told I'm still chaining (which I am), the only solution I can think of is to repeat data that could be accessible via associations.

But I hate repeating data! This is due to following DHH's Rails tutuorial where we re-create twitter, he showed how great it is to create relationships vs repeating data.

Should repeating data be appropriate to get the associations less chained?

Models, repeating data

class Country < ActiveRecord::Base    
  has_many :regions    
  has_many :counties    
  has_many :cities    
  has_many :people
end

class Region < ActiveRecord::Base
  has_one :country
  has_many :counties
  has_many :cities    
  has_many :people
end

class County < ActiveRecord::Base
  has_one :country
  has_one :region
  has_many :cities    
  has_many :people
end

class City < ActiveRecord::Base
  has_one :country
  has_one :region
  has_one :county    
  has_many :people
end

class Person < ActiveRecord::Base
  has_one :country
  has_one :region
  has_one :county    
  has_one :city
  has_many :relationships
  has_many :friends, :through => :relationships
end

vs models with chained associations

class Country < ActiveRecord::Base    
  has_many :regions   
end

class Region < ActiveRecord::Base
  belongs_to :country
  has_many :counties
end

class County < ActiveRecord::Base
  belongs_to :region
  has_many :cities
end

class City < ActiveRecord::Base
  belongs_to :county
end

class Person < ActiveRecord::Base
  belongs_to :city
end

لا يوجد حل صحيح

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top