I have the following hierarchy of classes:
public interface Message
public interface V2Message extends Message
public interface V3Message extends Message
I defined another interface to validate a message.
public interface Validation {
boolean validate(Message message);
}
Each class that implements Validation can deal with V2 and/or V3 messages, so in my implementation I have to distinguish the kind of message I want to validate because the code will be different.
public class MyValidation implements Validation {
public boolean validate(Message message) {
if(message instanceof V2Message) {
return validateV2((V2Message)message);
} else if (message instanceof V3Message) {
return validateV3((V3Message)message);
}
}
I was wondering if there is a way to remove the use of instanceof.
You could give
Validatetwo methods rather than one:That would also prevent passing in a simple
Messagebeing a runtime error. This is also a more accurate API, since you’ve said thatValidationimplementations can’t deal withMessage, onlyV2MessageandV3Message.