有3个不同的用户输入字段,如文本框和&在UI上下载。用户可以使用三个输入字段中的任何一个来搜索表,或者通过提供输入字段的不同组合来缩小结果集。我使用if else语句来使用这三个字段来实现我的逻辑,但问题是代码看起来非常如果在UI中添加了另外一个字段,那么很多if-else语句会更难看,那么我必须检查if else语句的更多组合。如果有人能够了解如何在这些场景中遵循最佳实践或更好的方法,我真的很感激。
我的代码:
public boolean filterResults(UserInputs userInputs){
String firstName = userInputs.getFirstName();
String lastName = userInputs.getLastName();
String phoneNumber = userInputs.getNumber();
//**search only by First Name**
if((firstName!=null && firstName!="")
&& (lastName==null || lastName=="" )
&& phoneNumber==null || phoneNumber ==""){
//logic to narrow down the result set based on condition met input values
list =DAO.getService(firstName);
return true;
}else if((lastName!=null && lastName!="")// **search only by Last Name**
&& (firstName== null || firstName == "")
&& (phoneNumber==null || phoneNumber == "")){
//logic to narrow down the result set based on condition met input values
list =DAO.getService(lastName); return true;
}else if((phoneNumber!=null && phoneNumber!="")// **Search Only by PhoneNumber**
&& (lastName==null || lastName=="" )
&& (firstName== null || firstName == "")){
//logic to narrow down the result set based on condition met input values
list =DAO.getService(phoneNumber); return true;
}else if((firstName!=null && firstName!="")// **Search by all params**.
&&(lastName!=null && lastName!="")
&& (phoneNumber!=null && phoneNumber!="")){
//logic to narrow down the result set based on condition met input values
list =DAO.getService(firstName, lastName, phoneNumber);
return true;
}else if((firstName!=null && firstName!="")//**Search by first&last name.**
&& (lastName!=null || lastName!="" )
&& (phoneNumber==null || phoneNumber =="")){
//logic to narrow down the result set based on condition met input values
list =DAO.getService(firstName, lastName);
return true;
}else if (.......){// **Search by last name & phone number.**
return true;
}else if (.........){// **Search by phone number & first name.**
return true;}
return false;
}
答案 0 :(得分:2)
现在,您的逻辑等同于这一行:
return (firstName != null && !firstName.isEmpty()) ||
(lastName != null && !lastName.isEmpty()) ||
(phoneNumber != null && !phoneNumber.isEmpty());
答案 1 :(得分:0)
您似乎正在为搜索条件的每种可能组合实施搜索方法。你不应该这样做。相反,过滤元素的方法应该测试每个标准:
public List<Element> search(List<Element> allElements, UserInputs criteria) {
List<Element> acceptedElements = new ArrayList<>();
for (Element e : allElements) {
if (isAccepted(e, criteria)) {
acceptedElements.add(e);
}
}
return acceptedElements;
}
private boolean isAccepted(Element e, UserInputs criteria) {
String firstName = criteria.getFirstName();
if (isCriterionFilled(firstName) && !hasFirstName(e, firstName)) {
return false;
}
String lastName = criteria.getLastName();
if (isCriterionFilled(lastName) && !hasLastName(e, lastName)) {
return false;
}
String phone = criteria.getPhone();
if (isCriterionFilled(phone) && !hasPhone(e, phone)) {
return false;
}
return true;
}