Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change my for loop full of if statements into more elegant/efficient code?

This is my string:

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

My method operates on this string and recognises if it contains the first= and second= substrings, and if yes - based on the true/false following it calls other methods. The first and second substrings may be optional though. This is what I have so far:

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

}

But perhaps there is a better/more efficient(and elegant?) way of solving that case?

like image 862
randomuser1 Avatar asked Dec 14 '22 09:12

randomuser1


1 Answers

Consider:

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

Above if can be coded as:

if (substring.contains("first") {
    String[] valueString = substring.split("=");            
    otherMethod("first", valueString[1]);
 }
like image 93
TryinHard Avatar answered May 24 '23 12:05

TryinHard