Say I have the following class:
class Cashier
def purchase(amount)
(@purchases ||= []) << amount
end
def total_cash
(@purchases || []).inject(0) {|sum,amount| sum + amount}
end
end
This is for learning purposes only, please ignore how unrealistic this may be.
Now in general, the total_cash could be an expensive call to loop through all the items.
I want to know how I can call .inject ONLY if the @purchases variable is dirty i.e. there was something modified.
How would my class be modified to do this?
The simplest approach would be to maintain another variable to indicate whether or not
@purchasesis dirty. For example:A cleaner/simpler approach may be to calculate
@total_casheach time the setter is called forpurchases. However, this means that you need to always use the setter, even within your class. It also means that you will be “hiding” an expensive operation inside of a setter method. You can decide which one you like better.I would also recommend against your naming scheme for an expensive operation. I would rename
total_cashto something likecalc_total_cashin order to tell users of your API that this is a relatively expensive call as opposed to a simple getter/setter.