我创建了一个跟踪汽车里程和服务历史的程序,以便更新用户即将到来的汽车服务需求。这看起来像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
类中?