mercredi 15 février 2017

Refactoring code with too many switch cases

I have inherited an application which needs some refactoring. The following is giving me some headaches. The original source code has too many switch cases like the following:

class Girl {
    //...
    void traditionalMakeUp() {
        switch (type) {
            case FRENCH:
                frenchMakeUp();
                break;
            case AFRICAN:
                africanMakeUp;
                break;
            case NORWEGIAN:
                norwegianMakeUp();
                .....

            case KOREAN:
                koreanMakeUp();
                .....
        }
    }
}

I am trying to refactor it like this:

abstract class Girl {
    //...
    abstract void makeUp();
}

class French extends Girl {
    void makeUp() {
        // makeUP
    }
}
class African extends Girl {
    void makeUp() {
        // makeUP
    }
}
class Norwegian extends Girl {
    void makeUp() {
        // makeUP
    }
}

// Somewhere in client code
girl.makeUp();

Is it the correct way to do it? If I didn't have 20+ cases in my switch, the strategy pattern would be fine.

Furthermore, I am reluctant to add 20+ classes just to fit the strategy design pattern. Is there another good way to refactor it?

Aucun commentaire:

Enregistrer un commentaire