lundi 22 novembre 2021

How to avoid instanceOf and dynamic getter check?

This code is from the CardUtility class I am using in my application.

    public static boolean areBothColoredAndHaveSameColor(Card c1, Card c2) {
        if (c1 instanceof ColoredCard coloredCard1 && c2 instanceof ColoredCard coloredCard2)
            return coloredCard1.getColor() == coloredCard2.getColor();
        return false;
    }

    public static boolean areBothNumberedAndHaveSameNumber(Card c1, Card c2) {
        if (c1 instanceof NumberedCard numberedCard1 && c2 instanceof NumberedCard numberedCard2)
            return numberedCard1.getNumber() == numberedCard2.getNumber();
        return false;
    }

    public static boolean areBothSpecialAndHaveSameSpeciality(Card c1, Card c2) {
        if (c1 instanceof SpecialColoredCard specialColoredCard1 && c2 instanceof SpecialColoredCard specialColoredCard2)
            return specialColoredCard1.getSpeciality() == specialColoredCard2.getSpeciality();
        return false;
    }

I can obviously see the code duplication happening here but I am bound by the fact that I can't use an equals check and because of the inheritance hierarchy: NumberedCard and SpecialColoredCard both extend the abstract ColoredCard class. How can I avoid the redundancy? Should I make all of these implement a new CardWithKeyProperty interface and refactor these methods to a single doBothHaveTheSameKeyProperty() method? But again I am not sure because ColoredCard is one step higher in the inheritance hierarchy so all of them implementing the same interface doesn't sound right.

Aucun commentaire:

Enregistrer un commentaire