Is it bad practice to use the instanceof operator in the following context?
public interface IWriter {
public abstract void write(Dto dto);
}
public abstract class Dto {
private long id;
public void setId(long id) {this.id = id;}
public long getId() {return id;}
}
public class DtoA extends Dto {
...
}
public class DtoB extends Dto {
...
}
public class MyWriterA implements IWriter {
@Override
public void writer(Dto dto) {
if (!(dto instanceof DtoA))
return;
...
}
}
public class MyWriterB implements IWriter {
@Override
public void writer(Dto dto) {
if (!(dto instanceof DtoB))
return;
...
}
}
There is a lot of myths about the use of that operator and I am not completely
sure that what I am doing is not bunk.
I have a lot of different writer implementations
which I want to combine in one interface. The problem is not every DTO is applicable for every writer. In my actual code there is a deep hierarchy of DTOs, which extend DtoA and DtoB, and either the
hierarchy branch of DtoA or DtoB is applicable for a writer, but only in a few cases both.
Should I avoid using the abstract class Dto as argument for the abstract write(Dto dto) method?
EDIT: Please read the comments on the accepted answer.
How is the code calling the IWriter? Presumably you’ve got to determine the type up there too? In which case you already know what kind of writer you need. You’re already dispatching on the basis of Type.
Your writers are not really substitutable WriterA only does As and so on. In which case you’re not gaining anything by claiming they are in an inheritance hierarchy.