2

I often find myself doing lots of delegating.

In Ruby Science, it says:

Many delegate methods to the same object are an indicator that your object graph may not accurately reflect the real world relationships they represent.

and

If you find yourself writing lots of delegators, consider changing the consumer class to take a different object. For example, if you need to delegate lots of User methods to Account, it’s possible that the code referencing User should actually reference an instance of Account instead.

I don't really understand this. What is an example of how this would look in practice?

ben
  • 29,229
  • 42
  • 124
  • 179
  • I have a copy of Ruby Science. If you read on a little more into the next paragraphs this should make sense. – Kenny Meyer Nov 22 '13 at 22:13
  • While interesting, the question is ripe for giving opinions, and this probably makes it off topic. I, for one, think the two quotes you mention are utterly wrong without more context: Delegation is an ubiquitous pattern in MVC, and if you need to delegate a lot of User methods to Account, you're doing at least a few things right, aka separation of concerns and (in ruby's own way) dependency injection. – Denis de Bernardy Nov 22 '13 at 22:14

1 Answers1

0

I think the author of that chapter wants to make clear, that, for example, writing:

class User
  def discounted_plan_price(discount_code)
    coupon = Coupon.new(discount_code)
    coupon.discount(account.plan.price)
  end
end

Notice account.plan.price, could be better done by using delegate on the user model, such as:

class User
  delegate :discounted_plan_price, to: :account
end

which allows you to write the following:

class User
  def discounted_plan_price(discount_code)
    account.discounted_plan_price(discount_code)
  end
end

class Account
  def discounted_plan_price(discount_code)
    coupon = Coupon.new(discount_code)
    coupon.discount(plan.price)
  end
end

Notice that we write plan.price, instead of account.plan.price, thanks to the delegate.

Good example, but there are many more.

Kenny Meyer
  • 7,849
  • 6
  • 45
  • 66
  • In other words, this is a case where more delegation is *good*, rather than bad - i.e. the opposite of what OP is requesting. (Not saying you're wrong, btw; on the contrary.) – Denis de Bernardy Nov 22 '13 at 22:25
  • I'd be happy to see examples where the Law of Demeter is inherently wrong. :-) – Kenny Meyer Nov 22 '13 at 22:43