我有 rest API,它使用多个参数(作为请求参数)来搜索实体。此搜索可能有多种变体。以下方法在末尾调用以使用给定参数搜索实体。
public List<Person> searchPerson(final String name,
final String city, final String state, final String code) {
if( name != null && city != null && state != null && code != null ){
//Search person in database with above all parameters
//personRepositoy is spring data repository.
personRepositoy.findByNameAndCityAndStateAndCode(name, city, state, code);
} else if( city != null && state != null && code != null){
personRepositoy.findByCityAndStateAndCode(name, city, state, code)
}
}
有什么方法可以避免在这里出现复杂的(容易出错,重构起来不那么容易)分支?可能正在使用集合或函数式编程概念?我真的不喜欢写这种分支代码(因为这些代码很难维护)
最佳答案
您可以像这样创建自己的实用程序:
public static boolean requireNonNull(Object... objects) {
for(Object obj : objects) {
if(obj == null) return false;
}
return true;
}
示例用法
public List<Person> searchPerson(final String name, final String city,
final String state, final String code) {
if(MyUtilityClass.requireNonNull(name, city, state, code)) {
//Search person in database with above all parameters
//personRepositoy is spring data repository.
personRepositoy.findByNameAndCityAndStateAndCode(name, city, state, code);
} else if(MyUtilityClass.requireNonNull(city, state, code)) {
personRepositoy.findByCityAndStateAndCode(city, state, code)
}
}
关于java - 避免复杂 if else 分支的最佳方法 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49917174/