Ruby取消对象创建

时间:2013-03-19 12:31:44

标签: ruby object constructor

如果错误参数,如何取消对象创建? 例如:

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

2 个答案:

答案 0 :(得分:4)

这很简单,只是不要使用构造函数。 :)

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

顺便说一句,这个模式称为工厂方法。

答案 1 :(得分:1)

除非您需要某种静默故障模式来处理错误数据,否则您可能只是想提出错误并停止程序:

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

是否使用此方法,或者通过错误输入的工厂方法取决于您希望使用的数据类型。

就个人而言,我几乎总是会提出错误,除非我有一个特定的要求,默默地忽略坏数据。但这是编码哲学,并不一定是你问题的最佳答案。

相关问题