在这个例子中使用多个else if语句是不好的做法?

时间:2016-12-11 19:18:06

标签: java android

我正在使用多个其他ifs来使程序根据旋转器中当前选择的值执行某些操作,但我不禁认为有更简洁的方法来执行此操作。有什么建议吗?

    if(spinnerinput.equals(spinnerinput2)) {
        output.setText(input.getText());
    }

    else if(spinnerinput.equals("Base 2") && spinnerinput2.equals("Base 10")) {
        String regex = "[0-1]+";

        if (input.getText().toString().matches(regex)) {
            output.setText(binaryToDecimal(input.getText().toString()));
        } else {
            Context context = getApplicationContext();
            CharSequence text = "Invalid characters for a binary number!";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    }

    else if(spinnerinput.equals("Base 10") && spinnerinput2.equals("Base 2")) {
        String regex = "[0-9]+";

        if(input.getText().toString().matches(regex)) {
            output.setText(decimalToBinary(input.getText().toString()));
        } else {
            Context context = getApplicationContext();
            CharSequence text = "Invalid characters for a decimal number!";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    }

1 个答案:

答案 0 :(得分:3)

您的if-else没有太大问题,但您可以将代码重构为最小化。您的最后两个条件块仅在CharSequence文本中有所不同。为什么不将它转换为方法并再次使用相同的代码?

private void yourCurrentMethod() {

    if(spinnerinput.equals(spinnerinput2)) {
        output.setText(input.getText());
    }

    else if(spinnerinput.equals("Base 2") && spinnerinput2.equals("Base 10")) {
        String regex = "[0-1]+";
        boolean isBinary = true;
        doSomething(isBinary, "Invalid characters for a binary number!");
    }

    else if(spinnerinput.equals("Base 10") && spinnerinput2.equals("Base 2")) {
        String regex = "[0-9]+";
        boolean isBinary = false;
        doSomething(isBinary, "Invalid characters for a decimal number!");
    }
}

private void doSomething(boolean isBinary, CharSequence text){
    if(input.getText().toString().matches(regex)) {
        if(isBinary){
            output.setText(binaryToDecimal(input.getText().toString()));
        } else {
            output.setText(decimalToBinary(input.getText().toString()));
        } 
    } else {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
}