我如何在此处重构这段代码以获得相同的结果?

How could I refactor this bit of code here to achieve the same result?

我正在为学校开发一个应用程序。我正在查看代码,发现我做的这个东西:

if (answerTxt1.getText().toString().matches("")) {
        infoStatus.setText("Answer1 cannot be empty!");
        return;
   } else if (answerTxt2.getText().toString().matches("")){
        infoStatus.setText("Answer2 cannot be empty!");
        return;
   } else if (answerTxt3.getText().toString().matches("")){
        infoStatus.setText("Answer3 cannot be empty!");
        return;
   } else if (answerTxt4.getText().toString().matches("")){
       infoStatus.setText("Answer4 cannot be empty!");
       return;
    }

这个'logic'背后的想法是在应用程序上有4个插槽可以写,但none不能为空。如果其中一个为空,名为 infoStatus 的 textView 将显示有关发生异常的消息。

我知道这可以进行重构并且可以用更少的代码完成,但我不确定如何进行。到目前为止,我的想法是这样的:

if (answerTxt1.getText().toString().matches("") 
             || answerTxt2.getText().toString().matches("")
             || answerTxt3.getText().toString().matches("")
             || answerTxt4.getText().toString().matches("")) {

       infoStatus.setText("One of the answers is empty!");
       return;
    }

但我不会收到 answerTxt# 为空的用户的特定消息。

如果您定义一个方法来检查任意文本视图是否为空,如果为空则设置错误字段,如下所示:

boolean checkEmpty(TextView textView, String name) {
   if (textView.getText().length() == 0) {
        infoStatus.setText(name + " cannot be empty!");
        return true;
   }
   return false;
}

然后你就可以摆脱代码中的大部分重复:

if (checkEmpty(answerTxt1, "answerTxt1")) {
    return;
}
if (checkEmpty(answerTxt2, "answerTxt2")) {
    return;
}
...

您可以更进一步,通过创建数据结构来保存您的文本视图和错误消息,但这样做的代价是使代码更加复杂、僵硬和脆弱。

你可以这样做

TextView[] textViews = {answerTxt1, answerTxt2, answerTxt3, answerTxt1};
for(int i=0; i<textViews.length; i++){
    if(textViews[i].getText().toString().isEmpty()){
        infoStatus.setText("Answer"+ (i+1) + " cannot be empty!");
        break;
    }
}