Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    };
}
like image 980
Jonas Schumacher Avatar asked Dec 05 '25 14:12

Jonas Schumacher


1 Answers

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){
        // ...
    }
}
like image 89
flakes Avatar answered Dec 08 '25 02:12

flakes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!