mercredi 8 août 2018

How to avoid unchecked call warning in interface implementations with factory

I'm facing a problem that I think that is related to the initial design but I don't find any way to fix it.

Let's supose I have the following generic interface (it's generic because all implementations use one different item to process):

public interface AlgorithmCalculator<T> {
    AlgorithmItem getSample(int days, List<T> dataItems);

    AlgorithmDetail getAlgorithmDetail();
}

Now, depending of which algorithm we are using I have one implementation or another, I will show you one implementation example:

public class Algorithm1Calculator implements AlgorithmCalculator<Item> {

    @Override
    public AlgorithmItem getSample(int days, List<Item> itemDataList) {
        // some stuff
    }

    @Override
    public AlgorithmDetail getAlgorithmDetail() {
        return AlgorithmDetail.getDetail1();
    }
}

As you can see that implementation makes some calculations (which are not relevant for my problem) and returns an object. In order to diferentiate which algorithm is being executing I have an algorithm detail which is different for any algorithm that I have.

As I want to have all code genric and I'm trying to avoid using switches or if-else for every possible algorithm, I have a factory class AlgorithmCalculatorFactory which consists in Map<AlgorithmDetail, AlgorithmCalculator>, which returns the implementation I need given an algorithm detail.

How I use it? By this way:

AlgorithmItem aItem = AlgorithmCalculatorFactory.getCalculatorService(algorithmDetail)
            .getSample(days, otherItem.getItemsList());

Note that the following would return an Algorithm1Calculator:

AlgorithmCalculatorFactory.getCalculatorService(algorithmDetail)

Until here everything is fine and this is currently working, but I don't like warnings and the current implementation gives me one:

Unchecked call to 'getSample(int days, List<T>)' as a member of raw type 'AlgorithmCalculator'.

Obviously it gives me warning as the interface is generic <T> but the factory returns an AlgorithmCalculator without type as I don't know which type will need until I get it.

I tried to do it using enums instead of factory class, but I get the same problem.

Any idea on how fix the warning?

Aucun commentaire:

Enregistrer un commentaire