Skip to content

Instantly share code, notes, and snippets.

@Jacobkg
Created July 3, 2012 05:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jacobkg/3037786 to your computer and use it in GitHub Desktop.
Save Jacobkg/3037786 to your computer and use it in GitHub Desktop.
Trying to respect the law of demeter
class User < ActiveRecord::Base
belongs_to :account
#A number of methods giving this class too many responsibilities already
end
class Account < ActiveRecord::Base
# t.integer credits
def add_credit(amount)
def available_credit
def deduct_credit(amount)
end
#The question is, is there any way to avoid writing code of the form "user.account.add_credit", and thus violating the law of demeter.
# For example:
def bill_user(user, amount)
if user.account.available_credits > amount
user.account.deduct_credits(amount)
else
#Charge user's credit card
end
end
@Jacobkg
Copy link
Author

Jacobkg commented Jul 3, 2012

Say that we have a user class (above) with the typical problem of having too many responsibilities. We are trying to introduce the concept of "prepaid credits" so that when we bill a user instead of charging their # card, we can deduct credits instead. We want to add some methods like "add_credit" and "available_credits". We want to avoid adding these methods to User.

One idea I had was to create an Account object (see above), and define the methods on that.

The question is, is there any way to avoid writing code of the form "user.account.add_credit", and thus violating the law of demeter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment