Java 如何重构只有变量不同的代码

Java 如何重构只有变量不同的代码,java,refactoring,Java,Refactoring,大家好:我正在开发两个java程序,两者之间的唯一区别是定义二维数组的开始语句。我在下面的示例中大幅缩短了代码: public class Qwerty { /** this is what needs to be replaced */ private static char master[][] = { QwertyKbd.lIndex, QwertyKbd.lMiddle, QwertyKbd.lRing, Q

大家好:我正在开发两个java程序,两者之间的唯一区别是定义二维数组的开始语句。我在下面的示例中大幅缩短了代码:

public class Qwerty {
    /** this is what needs to be replaced */
    private static char master[][] = {
        QwertyKbd.lIndex,
        QwertyKbd.lMiddle,
        QwertyKbd.lRing,
        QwertyKbd.lPinky,
            /** and so forth in this fashion */
    };

    public static int[] analyze(String file) {
    }

    public static void split(char c) {
    }
}
第二节课在这里:

 public class Dvorak{
        /** this is what needs to be replaced */
        private static char master[][] = {
            /** various definitions, eliminated for conciseness */
        };

        public static int[] analyze(String file) {
            /** this is the same*/
        }

        public static void split(char c) {
            /** this is the same*/
        }
    }

问题是我如何重构一个类,其中唯一的区别是“主”二维数组?钩子方法等在这里是愚蠢的。因为程序所做的一切都不需要修改。你觉得怎么样?

这似乎是继承的经典案例。继承的真正目的是代码重用,这正是您在这里得到的。我会使所有方法都是非静态的,并对它们执行“提取超类”,将
analyze()
split()
拉入抽象类,并添加一个抽象
getMaster()
或类似的方法,每个类都会覆盖该方法以返回适当的值


更糟糕的选择——有几个原因,但主要是因为它让你处于“静态地带”,这是一个可怕的地方——就是简单地将
analyze()
split()
移动到某个第三类中,这是你“共享”的地方像这样的实用方法。

如果您的类在不同的项目中,您就不能这样做 但如果它们是项目的一部分,您可以为所有类创建一个抽象类或超类:Qwerty、Dvorak。。。 例如,您创建了一个摘要

public class CustomAbstract{
    protected char master[][];
    public int[] analyze(String file){return null;};
    public void split(char c){};
}
然后在类中扩展这个抽象类

public class Qwerty extends CustomAbstract{
    public Qwerty(){
        //master = ...;
    }
    //your code
}
当您重构CustomAbstract中的master字段时,其他类中的所有master字段也将重构

上面代码的问题是,您不能使用静态字段主控,即使静态方法分析等。可能您需要类中的所有方法和字段都是静态的,您可以使用单骨架模式。在每个类中,您都会创建这样一个静态方法

public class Qwerty extends CustomAbstract{
    //your code
    static Qwerty instance = new Qwerty();
    public static Qwerty getInstance(){
        return instance;
    }
}
然后,您可以使用Qwerty.getInstance().analyze(字符串),而不是使用Qwerty.analyze(字符串)
希望对您有所帮助。

@minitech:继承所有静态字段和方法?如果不改进他的类,继承将一事无成。对于原始海报:摆脱静态,使用实例字段和方法,并请阅读一些介绍类和方法使用的教程。@HovercraftFullOfEels:Ah,我完全没有注意到它们是静态的。抱歉:如果课程在不同的项目中,你为什么不能这样做?为什么您需要一个抽象类?实际上,如果IDE支持您,您可以这样做!!!。重构并没有取代。如果替换,唯一需要的是所有类都有同名“master”的字段,但如果重构,所有类都必须有相同的上下文,例如,所有类都有相同的字段“master”继承自超类/抽象类+1-Java是一种OO语言,而您(@franklin)需要从对象的角度来思考。
static
关键字应谨慎使用。。。