如何改进重复代码

时间:2017-08-22 15:40:02

标签: java

我正在尝试以3种颜色组合打开和关闭一组20个灯

组合变为RED GREEN WHITE

RGW RGW RGW RGW RGW RGW RG

目前,我已经对重复序列进行了硬编码但是想知道如何改进它。 (P.S开始学习JAVA之旅)。

我想知道我可以学习哪种方法或练习来缩短这段代码。

     if ( Num == 1){
        System.out.println("RED is On");//1
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Red is Off");

        System.out.println("Green is On");//2
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Green is Off");

        System.out.println("White is On");//3
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("White is OFF");

        System.out.println("RED is On");//4
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Red is Off");

        System.out.println("Green is On");//5
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Green is Off");

        System.out.println("White is On");//6
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("White is OFF");

        System.out.println("RED is On");//7
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Red is Off");

        System.out.println("Green is On");//8
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Green is Off");

        System.out.println("White is On");//9
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("White is OFF");

        System.out.println("RED is On");//10
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Red is Off");

        System.out.println("Green is On");//11
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Green is Off");

        System.out.println("White is On");//12
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("White is OFF");

        System.out.println("RED is On");//13
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Red is Off");

        System.out.println("Green is On");//14
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Green is Off");

        System.out.println("White is On");//15
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("White is OFF");

        System.out.println("RED is On");//16
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Red is Off");

        System.out.println("Green is On");//17
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Green is Off");

        System.out.println("White is On");//18
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("White is OFF");

        System.out.println("RED is On");//19
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Red is Off");

        System.out.println("Green is On");//20
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Green is Off");

    } 

4 个答案:

答案 0 :(得分:3)

这是在无限循环中执行此操作的众多可能性之一:

String[] color = new String[]{"Red", "Green", "White"};
int counter = 0;
while (true) {
    System.out.println(color[counter] + " is On");
    TimeUnit.MILLISECONDS.sleep(500);
    System.out.println(color[counter] + " is Off");

    counter++;

    if (counter > 2) {
        counter = 0;
    }
}

答案 1 :(得分:1)

这里有两种重复性:

  1. 你重复几乎相同的代码,但改变了一件小事(颜色)
  2. 稍后,您一遍又一遍地重复完全的代码块
  3. (1)的解决方案是将重复的代码提取到方法中,将更改的元素作为参数传入:

     private void flash(String color) {
        System.out.println(color + " is On");
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println(color + " is Off");
     }
    

    然后根据需要调用它:

     flash("Green");
     flash("RED");
     flash("White");
     // etc.
    

    (2)的解决方案是使用循环表示重复。

    您的代码似乎重复了红绿白,因此您可以在flash()循环中调用for

     for(int i=0; i<5; i++) {   // 5 picked arbitrarily
         flash("RED");
         flash("Green");
         flash("White");
     }
    

    你甚至可以在循环中放置一个循环:

     List<String> colors = Arrays.asList("RED", "Green", White");
     for(int i=0; i<5; i++) {   // 5 picked arbitrarily
         for(String color : colors) {
             flash(color);
         }
     }
    

答案 2 :(得分:0)

你可以传递字符串&#39;颜色&#39;将blinker()作为参数使其可重用。从你的代码顶部的条件中猜测我假设你有多个模式要闪烁。在这种情况下,每个模式定义一个单独的字符串&#39;颜色&#39;并且一旦请求模式 - 将其提供给闪光灯()。您的代码既易读又易于维护。

public void blinker() {


    String colors = "GWB GWB GWB GW GW GWWWW GWBB BWG";


    for (char c : colors.toCharArray()) {
        String colorName;
        switch (c) {
            case 'G':
                colorName = "GREEN";
                break;
            case 'W':
                colorName = "WHITE";
                break;
            case 'B':
                colorName = "BLUE";
                break;
            case ' ':
                continue;
            default:
                System.err.println("Unknown color: " + c);
                continue;
        }
        try {
            doBlink(colorName, 500);
        } catch (Exception ignore) {}
    }

}

public void doBlink(String color, long duration) throws InterruptedException {
    System.out.println(String.format("%s is On", color));
    TimeUnit.MILLISECONDS.sleep(duration);
    System.out.println(String.format("%s is Off", color));
}

输出如下:

GREEN is On
GREEN is Off
WHITE is On
WHITE is Off
BLUE is On
BLUE is Off
GREEN is On
...

答案 3 :(得分:0)

再添加一个:

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

public class Test{
    public static void main(String [] args){        
        IntStream.rangeClosed(1, 20).forEach(i->{
            try {
                onOff(i);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        });        
    }

    private static void onOff(int i) throws InterruptedException {
        String color = getColor(i);
        System.out.println(color+" is On");
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println(color+" is Off");
    }

    private static String getColor(int i) {
        return i%3 == 1? "RED": i%3 == 2? "Green" : "White";
    }
}