在 class 定義里使用一致的結構。
class Person # extend and include go first extend SomeModule include AnotherModule # constants are next SOME_CONSTANT = 20 # afterwards we have attribute macros attr_reader :name # followed by other macros (if any) validates :name # public class methods are next in line def self.some_method end # followed by public instance methods def some_method end # protected and private methods are grouped near the end protected def some_protected_method end private def some_private_method end end
傾向使用 module,而不是只有類方法的 class。類別應該只在創建實例是合理的時候使用。
# bad class SomeClass def self.some_method # body omitted end def self.some_other_method end end # good module SomeClass module_function def some_method # body omitted end def some_other_method end end
當你希望將模塊的實例方法變成 class 方法時,偏愛使用 module_function 勝過 extend self。
# bad module Utilities extend self def parse_something(string) # do stuff here end def other_utility_method(number, string) # do some more stuff end end # good module Utilities module_function def parse_something(string) # do stuff here end def other_utility_method(number, string) # do some more stuff end end
When designing class hierarchies make sure that they conform to the
Liskov Substitution Principle.
在設計類層次的時候確保他們符合 Liskov Substitution Principle 原則。(譯者注: LSP原則大概含義為: 如果一個函數中引用了 父類的實例, 則一定可以使用其子類的實例替代, 并且函數的基本功能不變. (雖然功能允許被擴展))
Liskov替換原則:子類型必須能夠替換它們的基類型 <br/>
1. 如果每一個類型為T1的對象o1,都有類型為T2的對象o2,使得以T1定義的所有程序P在所有的對象o1都代換為o2時,程序P的行為沒有變化,那么類型T2是類型T1的子類型。 <br/>
2. 換言之,一個軟件實體如果使用的是一個基類的話,那么一定適用于其子類,而且它根本不能察覺出基類對象和子類對象的區別。只有衍生類替換基類的同時軟件實體的功能沒有發生變化,基類才能真正被復用。 <br/>
3. 里氏代換原則由Barbar Liskov(芭芭拉.里氏)提出,是繼承復用的基石。 <br/>
4. 一個繼承是否符合里氏代換原則,可以判斷該繼承是否合理(是否隱藏有缺陷)。
新聞熱點
疑難解答