这是我的字符串:
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");
}
}
}
}
但是也许有一种更好/更有效(优雅的方法)来解决这种情况?
考虑:
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]);
}
布尔值具有两种状态,即true或false。您可以在有或没有标志的情况下表达这一点,例如:
"first`, second"
-> first和second为真。
现在您可以重构代码:
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
而不将布尔值当作字符串。
您不需要所有的if
语句。
您可以再次按=
分割每个子字符串:
void method(String field) {
String[] splittedField = field.split(", ");
for (String substring : splittedField) {
String[] args = substring.split("=");
otherMethod(args[0], args[1]);
}
}