when a new type is added to class A , should the compiler mark all switch that need to be adjusted?
A good approach to this would be to replace switch with a more robust implementation of multiple sending, such as the Visitor Template :
interface VisitorOfA { Object visitA(A a); Object visitB(B b); } class A { Object accept(VisitorOfA visitor) { return visitor.visitA(this); } } class B extends A { Object accept(VisitorOfA visitor) { return visitor.visitB(this); } }
Using this infrastructure, you can remove your switch by replacing them with a visitor implementation:
Object res = a.accept(new VisitorOfA() { public Object visitA(A a) { return new Bla(); } public Object visitB(B b) { return new Cop(); } });
When you add a new subtype to A , say class C , all you have to do is add a new method to VisitorOfA :
Object visitC(C c);
Now the compiler will detect all the places where this new method has not been implemented, which avoids run-time problems.
source share