在我的一个项目中,我有两个“数据传输物体”记录Type1和记录Type2, 继承一个抽象的记录类别。
I want both RecordType objects to be processed by the same RecordProcessor class within a "process" method. My first thought was to create a generic process method that delegates to two specific process methods as follows:
public RecordType process(RecordType record){
if (record instanceof RecordType1)
return process((RecordType1) record);
else if (record instanceof RecordType2)
return process((RecordType2) record);
throw new IllegalArgumentException(record);
}
public RecordType1 process(RecordType1 record){
// Specific processing for Record Type 1
}
public RecordType2 process(RecordType2 record){
// Specific processing for Record Type 2
}
I ve 读到Scott Meyers在Effective C++上写道:
"Anytime you find yourself writing code of the form if the object is of type T1, then do something, but if it s of type T2, then do something else, slap yourself."
如果他正确的话,我显然应该 myself笑自己。 我看不出这种设计是坏的(当然,除非有人在记录Type3中填加,而没有在处理这种设计的通用“程序”方法中增加另一行,从而形成一种NPE),而且我认为,其他办法可以涉及将具体处理逻辑的首当其冲放在记录Type班上,而记录Type课程本身对我来说确实没有什么意义,因为从理论上讲,我喜欢在这些记录上进行的各种处理。
某人能否解释为什么可能认为这种设计不好,并提供某种替代方法,仍然把处理这些记录的责任交给“处理”类别?
<><>UPDATE:
- Changed
return null
tothrow new IllegalArgumentException(record);
- Just to clarify, there are three reasons a simple RecordType.process() method would not suffice: First, the processing is really too far removed from RecordType to deserve its own method in the RecordType subclasses. Also, there are a whole slew of different types of processing that could theoretically be performed by different processors. Finally, RecordType is designed to be a simple DTO class with minimal state-changing methods defined within.