Is This Use of the “instanceof” Operator Considered Bad Design?

后端 未结 6 551
南方客
南方客 2020-11-30 04:11

In one of my projects, I have two \"data transfer objects\" RecordType1 and RecordType2 that inherit from an abstract class of RecordType.

I want both RecordType obj

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 04:40

    Design is a means to an end, and not knowing your goal or constraints, nobody can tell whether your design is good in that particular situation, or how it might be improved.

    However, in object oriented design, the standard approach to keep the method implemention in a separate class while still having a separate implementation for each type is the visitor pattern.

    PS: In a code review, I'd flag return null, because it might propagate bugs rather than reporting them. Consider:

    RecordType processed = process(new RecordType3());
    
    // many hours later, in a different part of the program
    
    processed.getX(); // "Why is this null sometimes??"
    

    Put differently, supposedly unreachable code paths should throw an exception rather than result in undefined behaviour.

提交回复
热议问题