【发布时间】:2011-05-26 04:26:16
【问题描述】:
我创建了一个程序来跟踪汽车里程和服务历史记录,以便为用户更新汽车即将到来的服务需求。
我有三个班级: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 在“Ruby 编程”中的论点),我什至可以测试是否可以添加CarServiceHistoryEntry?我不能只传递一个String而不是在我的单元测试中设置然后添加CarServiceHistoryEntry吗? - 既然
CarHistory的唯一必要属性是entries数组和to_s方法,我是否应该将这个类全部废弃并将其放入car类中?
【问题讨论】:
标签: ruby duck-typing