3 回答

TA貢獻(xiàn)1776條經(jīng)驗(yàn) 獲得超12個(gè)贊
您可以做的一件事是將if檢查提取到一個(gè)單獨(dú)的方法中,您可以使用輸入、正則表達(dá)式和消息調(diào)用該方法:
private void validateInput(String input, String regex, String message) {
if (input != null && !input.matches(regex)) {
throw new IllegalArgumentException("Error Message :" + message);
}
}
public void validate(String firstName, String middleName, String lastName) {
this.validateInput(firstName, "^[a-zA-Z`’ -]{1,50}$",
"Invalid value for firstName field from Input Parameter");
this.validateInput(middleName, "^[a-zA-Z.`’ -]{0,50}$",
"Invalid value for middleName field from Input Parameter");
this.validateInput(lastName, "^[a-zA-Z`’ -]{2,50}$",
"Invalid value for lastName field from Input Parameter");
}

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
為什么不使用else if來防止消息被覆蓋?這樣代碼將在第一個(gè)匹配的條件下退出。這是假設(shè)您想堅(jiān)持您的實(shí)現(xiàn)而不是過多地編輯代碼。
public void validate(String firstName, String middleName, String lastName) {
String errorMessage = null ;
if (firstName != null && !firstName.matches("^[a-zA-Z`’ -]{1,50}$")) {
errorMessage = "Invalid value for firstName field from Input Parameter";
}else if (middleName != null && !middleName.matches("^[a-zA-Z.`’ -]{0,50}$")) {
errorMessage = "Invalid value for middleName field from Input Parameter";
}else if (lastName != null && !lastName.matches("^[a-zA-Z`’ -]{2,50}$")) {
errorMessage = "Invalid value for lastName field from Input Parameter";
}
if (errorMessage != null){
throw new IllegalArgumentException("Error Message :" + errorMessage);
}
System.out.println(firstName + " " + middleName + " " + lastName);
}

TA貢獻(xiàn)1966條經(jīng)驗(yàn) 獲得超4個(gè)贊
使用你的第二個(gè)想法......
public void validate(String firstName, String middleName, String lastName) {
String errorMessage = "Invalid value for fields %s from Input Parameter";
StringBuffer fields = new StringBuffer();
if (firstName != null && !firstName.matches("^[a-zA-Z`’ -]{1,50}$")) {
fields.append("firstName");
}
if (middleName != null && !middleName.matches("^[a-zA-Z.`’ -]{0,50}$")) {
fields.append(" middleName");
}
if (lastName != null && !lastName.matches("^[a-zA-Z`’ -]{2,50}$")) {
fields.append(" lastName");
}
if (fields.length() > 0){
throw new IllegalArgumentException("Error Message :" + String.format(errorMessage, fields.toString()));
}
System.out.println(firstName + " " + middleName + " " + lastName);
}
打電話給
validate("", "1", "");
輸出:
Exception in thread "main" java.lang.IllegalArgumentException: Error Message :Invalid value for fields firstName middleName lastName from Input Parameter
at Main.validate(Main.java:26)
at Main.main(Main.java:5)
exit status 1
打電話給
validate("Andres", "1", "Martinez");
輸出:
Exception in thread "main" java.lang.IllegalArgumentException: Error Message :Invalid value for fields middleName from Input Parameter
at Main.validate(Main.java:26)
at Main.main(Main.java:5)
exit status 1
添加回答
舉報(bào)