我正在用Product类用Ruby编写程序。每当使用错误类型的参数初始化Product时,我都会引发一些异常。有什么办法可以干燥提出的异常(我什至正确地引用了这些异常?),我感谢您的帮助。代码如下:
class Product
attr_accessor :quantity, :type, :price, :imported
def initialize(quantity, type, price, imported)
raise ArgumentError.new("Type must be a string") if type.class != String
raise ArgumentError.new("Quantity must be greater than zero") if quantity <= 0
raise ArgumentError.new("Price must be a float") if price.class != Float
@quantity = quantity
@type = type
@price = price.round(2)
@imported = imported
end
end
Run Code Online (Sandbox Code Playgroud)
惯用的方法是根本不行的类型检查,而是强制的传递的对象(使用to_s,to_f等):
class Product
attr_accessor :quantity, :type, :price, :imported
def initialize(quantity, type, price, imported)
raise ArgumentError.new("Quantity must be greater than zero") unless quantity > 0
@quantity = quantity
@type = type.to_s
@price = price.to_f.round(2)
@imported = imported
end
end
Run Code Online (Sandbox Code Playgroud)
然后,您将获得适当的String / Float / etc。传递的对象的表示形式,如果它们不知道如何强制使用这些类型(因为它们不响应该方法),则可以适当地获取NoMethodError。
至于数量检查,这看起来很像验证,您可能想将其引入一个单独的方法中(尤其是其中有很多方法):
class Product
attr_accessor :quantity, :type, :price, :imported
def initialize(quantity, type, price, imported)
@quantity = quantity
@type = type.to_s
@price = price.to_f.round(2)
@imported = imported
validate!
end
private
def validate!
raise ArgumentError.new("Quantity must be greater than zero") unless @quantity > 0
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4353 次 |
| 最近记录: |