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.
The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
instanceof can be used to test if an object is a direct or descended instance of a given class. instanceof can also be used with interfaces even though interfaces can't be instantiated like classes.
Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism".
Sometimes there's no getting around using instanceof
- there is no need to feel shame.
Typing IWriter may help:
public interface IWriter<T extends Dto> {
public abstract void write(T dto);
}
then
public class MyWriterA implements IWriter<DtoA> {
@Override
public void writer(DtoA dto) {
// No need for instanceof, because it can't be anything else
...
}
}
Perhaps a combination of such typing and Brian Agnew's worthy answer would do the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With