7
votes

Sec: minimiser le code répété en Java

J'écris une méthode en Java:

List<Foo> computeFooList(/* args */)
{
    return computeEitherList(/* args */, Foo.class);
}

List<String> computeStringList(/* args */)
{
    return computeEitherList(/* args */, String.class);
}

private List<???> computeEitherList(/* args */, Class<?> whichType)
{
    /* snip */
}


1 commentaires

Vous pourriez être intéressé par ce nouveau site Stackexchange: codereview.stackexchange.com


3 Réponses :


7
votes

Impossible d'extérioriser la logique de transformation en une stratégie distincte (telle que la fonction de GUAVA code>):

computeList(..., Functions.toStringFunction());


2 commentaires

Cela semble certainement prometteur. Permettez-moi de jouer avec cela.


Brillant! Merci. J'utilisais déjà Guava aussi. J'ai besoin de creuser plus profondément dedans.



0
votes

J'ai une interface "SearchFilter" et une classe abstraite "filtreur" que j'utilise d'une manière similaire à celle-ci. La logique de décision peut être faite indépendamment et de manière générique d'ajouter des choses à la liste de retour. Je vérifiais chaque foo et disant "vrai" incluez-le ou "FALSE" l'exclure.

public FooFilter extends FilterAdapter<Foo>
{
    public boolean include(Foo item)
    {
        if (item.isInvalid()) return false;
        // or any other complex logic you want
        return item.hasGoodThings();
    }
}


0 commentaires

0
votes

C'est un peu laids, mais je pense que cela pourrait fonctionner:

List<Foo> computeFooList(/* args */) {
    return computeEitherList(/* args */, Foo.class);
}

List<String> computeStringList(/* args */) {
    return computeEitherList(/* args */, String.class);
}

private <T> List<T> computeEitherList(/* args */, Class<T> whichType) {
    List<T> rval = new ArrayList<T>();
    for (Foo foo : listOfFoo) {
        // process foo

        if (whichType.equals(Foo.class)) {
            rval.add(whichType.cast(foo));
        }
        else if (whichType.equals(String.class)) {
            rval.add(whichType.cast(foo.toString()));
        }
        else {
            throw new SomeException("Cannot compute list for type " + whichType);
        }
    }
    return rval;
}


0 commentaires