【发布时间】:2016-07-16 15:57:23
【问题描述】:
我正在努力成为一个更好的开发人员,我总是问自己是否有更好的方法来做这些事情。这不是我第一次处理这个问题,所以我决定问问你是怎么想的。
假设我必须实现一个代表产品的类。
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
假设这个类的工作流程是创建一个产品,计算总价并将其导出以供将来使用。
不调用initialize中的set_gross_price方法对吗?
事实是,当您出口产品时,必须计算总价,但我认为正确的选择不是强迫开发人员在export 之前致电set_gross_price,但我也不确定第一个export 方法的行,因为集合应该关注设置总价格而不是检查它是否为空。
你有更好的方法来实现它吗?
谢谢
【问题讨论】:
-
嗯,这个问题可能更适合code review?
-
我认为您混合了两个问题(一个包含产品数据的对象以及您如何计算价格)
-
你能详细解释一下吗@pascalbetz
标签: ruby oop coding-style