Created
August 21, 2014 10:06
-
-
Save phuibonhoa/974aae201421f0177c92 to your computer and use it in GitHub Desktop.
use memoized attributes instead of process methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Memoized facade attribute | |
# √ Lazy loaded | |
# √ Better encapsulated / more 'atomic'. Processing introduces unnecessary depencies at different times of the life cycle of the object. | |
# √ More idiomatic mindset to think of these are 'attributes' on an object, than results of a calculation | |
# Memoized attribute | |
class RecommendationCalculator | |
attr_reader :user | |
def initialize(user:) | |
@user = user | |
end | |
def recommendations | |
@recommendations ||= ( | |
# calculate recommendations | |
) | |
end | |
end | |
# Process / Calculate method | |
class RecommendationCalculator | |
attr_reader :user, :calculated_recommendations | |
def initialize(user:) | |
@user = user | |
@calculated_recommendations = calculate_recommendations(user: user, location: user.current_location) | |
end | |
private | |
def calculate_recommendations(user:, location:) | |
# calcualte recommendations based on user and location | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is a "gotcha" when using
||=
memoization - specifically memoizing an object that evaluates tofalse
. This doesn't come up often, but can be a difficult to track down.