我創建了一個跟蹤汽車裏程和服務歷史的程序,以便更新用戶即將到來的汽車服務需求。這看起來像Ruby的鴨子打字一樣嗎?
我有三類:Car
,CarHistory
和CarServiceHistoryEntry
。第三個是直截了當的;它保持了與服務相關聯的所有屬性:日期,里程數,服務執行等CarHistory
類如下:
require_relative 'car_service_history_entry'
class CarHistory
attr_reader :entries
def initialize (*entry)
if entry.size > 1
@entries = []
else
@entries = entry
end
end
def add_service_entry entry
@entries << entry
end
def to_s
entries_string = ""
@entries.each {|entry| entries_string << "#{entry.to_s}\n"}
entries_string
end
end
- 在
initialize
,應該之類的entry
進行檢查? - 在
add_service_entry
,採用鴨子打字(如Andy Thomas在「Programming Ruby」中的說法),我甚至會測試是否可以添加CarServiceHistoryEntry
?難道我只是通過String
而不是在我的單元測試中設置並添加CarServiceHistoryEntry
? - 由於
CarHistory
的唯一必要屬性是entries
數組和to_s
方法,我應該只將這個類全部取消並放入car
類中?