如何取消对象创建,如果得到错误的参数?例子:
class MyClass
def initialize(a, b, c)
@a = @b = @c = nil
@a = a if a.is_a? Integer
@b = b if b.is_a? String
@c = c if c.is_a? Integer or c.is_a? Float
return nil if @a == nil or @b == nil or @c == nil # doesn't works
end
end
cl = MyClass.new('str', 'some', 1.0) # need cl to be nil because 1st param isn't Integer
这很简单,只是不要使用构造函数。:)
class MyClass
def initialize(a, b, c)
@a, @b, @c = a, b, c
end
def self.fabricate(a, b, c)
aa = a if a.is_a? Integer
bb = b if b.is_a? String
cc = c if c.is_a? Integer || c.is_a? Float
return nil unless aa && bb && cc
new(aa, bb, cc)
end
end
cl = MyClass.fabricate('str', 'some', 1.0) # => nil
顺便说一下,这个模式叫做工厂方法。
除非您需要某种静默故障模式来处理坏数据,否则您可能只是想引发错误并停止程序:
def initialize(a, b, c)
@a = @b = @c = nil
raise "First param to new is not an Integer" unless a.is_a? Integer
@a = a
raise "Second param to new is not a String" unless b.is_a? String
@b = b
raise "Third param to new is not an Integer or Float" unless c.is_a? Integer or c.is_a? Float
@c = c
end
您是使用这种方法,还是使用工厂方法来忽略错误的输入,取决于您希望处理的数据类型。
就我个人而言,我几乎总是会抛出错误,除非我有一个特殊的要求,默默地忽略坏数据。但这是一种编码哲学,并不一定是解决问题的最佳答案。