我如何在这里重构这段代码以达到相同的结果?

问题描述 投票:-2回答:2

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

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;
    }

此“逻辑”背后的想法是,有4个插槽可在应用程序上写入,但没有一个不能为空。如果其中一个为空,则名为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#为空的用户的特定消息。

java android refactoring
2个回答
1
投票

您可以这样做


1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.