2010-06-03 14 views
2

想象我有這樣一個類:將您的驗證代碼分組到一個Ruby方法中是一個壞主意?

class A 
    attr_accessor :a 
    attr_accessor :b 

    def check 
     raise "a must meet some condition" if !condition(@a) 
     raise "b must meet some condition" if !condition(@b) 
    end 

    def do_some_work 
     check() 
     # more work here 
    end 

    def do_some_more_work 
     check() 
     # other work here 
    end 
end 

它是不好的做法,有內部的另一種方法的訪問器的先決條件,而不是當前的一個?

回答

3

最好是檢查分配何時發生。 快速失敗。

class A 
    attr_reader :a, :b 

    def a=(new_a) 
    raise "a must meet some condition" if !condition(@a) 
    @a = new_a 
    end 

    def b=(new_b) 
    raise "b must meet some condition" if !condition(@b) 
    @b = new_b 
    end 

    def do_some_work 
    # Do the work, knowing @a and @b are valid 
    end 

    # ... 
end 
+1

如果條件包括檢查它們不是零怎麼辦? – Geo 2010-06-03 12:08:52

+1

@Geo,如果它們不應該是'nil',你可能想要將它們傳遞給構造函數。例如:A.new(:a =>「some value」,:b =>「another value」)或A.new(「some value」,「another value」)。 – molf 2010-06-03 12:59:42

相關問題