jeudi 2 août 2018

Refactoring a rigid code to eliminate if-else statement of checking instanceOf

Good day everyone,

I have a question regarding to refactoring a piece of code. The classes are structured as:

abstract class A
class A1 extends class A
class A2 extends class A
class A3 extends class A

abstract class AdditionalStuff {
    abstract void function(); 
}
class AdditionalStuffForA1 extends AdditionalStuff
class AdditionalStuffForA2 extends AdditionalStuff
class AdditionalStuffForA3 extends AdditionalStuff

class Implementation {
    List<A> aList; 
    .... //add A1, A2, A3 to aList

    AdditionalStuff aS;

    for (A instance: aList) {
        if(instance instanceOf A1)
            aS = new AdditionalStuffForA1();
        else if(instance instanceOf A2)
            aS = new AdditionalStuffForA2();
        else
            aS = new AdditionalStuffForA3();

        aS.function()
    }

}

The code above is rigid I think, because everytime when a new class An (for example A4 and AdditionalStuffForA4) is added, It's a must to modify the if else statements too.

I thought about using Decoration Pattern, but now I think Decoration Pattern cannot solve my problem. I would like to ask, could you please suggest me a way to refactoring the code above to eliminate the use of if-else statement? (Note that, I cannot add functions of AdditionalStuff to be inside A because they are used differently)

Aucun commentaire:

Enregistrer un commentaire