I'm trying to be a better developer and I always ask myself If there is a better way to do the things. Is not the first time that I have to deal with this problem so I decided to ask what you think about it.
Let's say I have to implement a class that represent a product.
class Product
def initialize (name, net_price)
@name = name
@net_price = net_price
@gross_price = nil
end
def set_gross_price
@gross_price = heavy_gross_price_calculation
end
def export
@gross_price.nil? && set_gross_price
return product.to_hash
end
def heavy_gross_price_calculation
# This function calculate the gross price but let's say that this is
# pretty onerous operation that involves maybe also an external API
# request
end
end
Let's say that the work flow for this class is create a product, calculate the gross price and export it for future use.
Is it correct to not call the set_gross_price
method in the initialize
?
The fact is that when you export a product the gross price have to be calculated but I don't think that the correct choise is to force the developer to call set_gross_price
before export
but also i'm not sure about the first line of the export
method beacause the set should concern about set the gross price and not check if it is null.
Do you have some better way to implement this?
Thanks