我如何将充满if语句的for循环更改为更优雅/更有效的代码?

问题描述 投票:3回答:3

这是我的字符串:

String field = "first=true, second=true"

我的方法对这个字符串进行操作,并识别它是否包含first=second=子字符串,如果是,则-基于其后的true / false调用其他方法。但是,第一和第二子字符串可能是可选的。这是我到目前为止的内容:

void method(String field) {

      String[] splittedField = field.split(", ");
      for (String substring : splittedField) {
          if (substring.contains("first") {
              if (substring.contains("true") {
                  otherMethod("first", "true");
              } else if (substring.contains("false") {
                  otherMethod("first", "false");
              }
          } else if (substring.contains("second") {
              if (substring.contains("true") {
                  otherMethod("second", "true");
              } else if (substring.contains("false") {
                  otherMethod("second", "false");
              }
          }
      }

}

但是也许有一种更好/更有效(优雅的方法)来解决这种情况?

java algorithm java-8 stream java-stream
3个回答
0
投票

考虑:

if (substring.contains("first") {
    if (substring.contains("true") {
        otherMethod("first", "true");
    } else if (substring.contains("false") {
        otherMethod("first", "false");
    }
 } 

if以上可以被编码为:

if (substring.contains("first") {
    String[] valueString = substring.split("=");            
    otherMethod("first", valueString[1]);
 }

0
投票

布尔值具有两种状态,即truefalse。您可以在有或没有标志的情况下表达这一点,例如:

"first`, second"-> firstsecond为真。

现在您可以重构代码:

void method(String field) {
    String[] splittedField = field.split(", ");
    if (substring.contains("first")) {
        otherMethod("first", "true");
    }
    else {
        otherMethod("first", "false");
    }
    if (substring.contains("second")) {
        otherMethod("second", "true");
    }
    else {
        otherMethod("second", "false");
    }
}

您可能也可以重构otherMethod而不将布尔值当作字符串。


0
投票

您不需要所有的if语句。

您可以再次按=分割每个子字符串:

void method(String field) {

    String[] splittedField = field.split(", ");
    for (String substring : splittedField) {
        String[] args = substring.split("=");            
        otherMethod(args[0], args[1]);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.