How refactor two methods which are very similar

别等时光非礼了梦想. 提交于 2020-03-03 04:50:46

问题


I have following classes:

public interface IBaseInterface {
    String baseMethod();
}

public class BaseClass implements IBaseInterface{

    @Override
    public String baseMethod() {
        return "baseInterface";
    }

    public String otherBaseMethod(){
        return "otherBaseMethod";
    }

}

public class ClassA implements IBaseInterface{

    @Override
    public String baseMethod() {
        return "ClassA";
    }

    public String getAttribiuteA(){
        return "A";
    }

}

public class ClassB implements IBaseInterface {

    @Override
    public String baseMethod() {
        return "ClassB";
    }

    public String getAttribiuteB(){
        return "B";
    }

}

And now I have two very similar methods:

private String getBaseMethod(){

    /** Do something */

    if(/**    */){
        BaseClass base = new BaseClass();
        return base.baseMethod();
    }else if (/**    */){
        ClassA a = new ClassA();
        return a.baseMethod();
    } else {
        ClassB b = new ClassB();
        return b.baseMethod();
    }
}

private String getOtherMethod(){

    /** Do something */

    if(/**    */){
        BaseClass base = new BaseClass();
        if(/**    */){
            return base.baseMethod();
        } else{
            return base.otherBaseMethod()
        }
    } else if(/**    */){
        ClassA a = new ClassA();
        return a.getAttribiuteA()
    } else{
        ClassB b = new ClassB();
        return b.getAttribiuteB();
    }
}

These two methods are very similar. In if-Clause are the same conditions. Can we make these two methods better? More "abstractly" ?

I can not make any changes in my classes, only in methods.


回答1:


I assume what is being asked here is to use 'Polymorphism'

Because all three classes, BaseClass, ClassA, and ClassB, all implement interfcae IBaseInterface, so you can do such thing like following example:

 IBaseInterface i1 = new BaseClass();
 IBaseInterface i2 = new ClassA();
 IbaseInterface i3 = new ClassB();

And as you already noticed at this point, you may use List to save your classes too.

 List<IBaseInterface> interfaces = new ArrayList<>();
 interfaces.add(i1);
 ....

and so on

Because IBaseInterface has method baseMethod(), now you can simply iterate through the list and invoke baseMethod() method for each IBaseInterface objects.

take a look for 'Polymorphic Behavior'



来源:https://stackoverflow.com/questions/43086489/how-refactor-two-methods-which-are-very-similar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!