Search code examples
javadesign-patternsisinstance

Avoiding isInstance statement


How can I refactor this example to avoid these kind of situation that I need to check isInstance in every data type? Is there any pattern that I can follow?

public interface GenericData {}

public interface IntegerData extends GenericData{
    public Integer Data();
}

public interface StringData extends GenericData{
    public String Data();
}

public interface Client {
    public boolean LoadData(GenericData data);
}

public class IntegerClientImpl implements Client{
    public boolean LoadData(GenericData data){
        return IntegerData.class.isInstance(data);
    };
}

Solution

  • You can use generics

    public interface Client<Data extends GenericData> {
        public boolean LoadData(Data data);
    }
    
    public class IntegerClientImpl implements Client<IntegerData> {
        @Override
        public boolean LoadData(IntegerData data){
            // ...
        }
    }