我正在编写一些CRUD应用程序的代码,该页面显示数据库表中的数据,并且应该与两个非常相似的表连接(由于历史原因或时间太长,这两个非常相似的表无法优化为一个表)。我确实使用switch
语句和Java 8函数进行了优化,但是Intellij IDEA在两个不知道如何解决它的switch语句之间给了我重复代码片段警告。
我不是要优化设计,而是重构重复的代码片段并修复此警告。
我有一种search
方法,用于从数据库中搜索数据,并通过TaxCustomerType
枚举使用来自不同表的单独逻辑:
public PageUtils<IndividualTaxactorVO> search(TaxCustomerType type,IndividualTaxactorQuery query,UserDO principal) {
//... ignore for conciseness
Function<actorCondition,Integer> counter;
Function<actorCondition,Collection<IndividualTaxactorVO>> searcher;
switch (type) {
case INDIVIDUAL: {
counter = individualTaxactordao::countIndividual;
searcher = individualTaxactordao::searchIndividual;
break;
}
case CORPORATE: {
counter = individualTaxactordao::countCorporate;
searcher = individualTaxactordao::searchCorporate;
break;
}
default:
throw new RuntimeException("不能识别的个税客户类型:" + type);
}
int total = counter.apply(condition);
if (total == 0) {
return PageUtils.empty();
}
Collection<IndividualTaxactorVO> list = searcher.apply(condition);
return new PageUtils<>(list,total);
}
我还有一个link
方法可以插入表中并进行一些检查,也可以使用TaxCustomerType
枚举使用单独的逻辑:
public void link(TaxCustomerType type,String customerId,UserDO principal) {
Function<String,IdAndTaxCodeAndDisabledOnly> findById;
BiFunction<String,String,Integer> existsCounter;
switch (type){
case INDIVIDUAL: {
findById = individualCustomerService::findTaxCodeAndDisabledById;
existsCounter = individualTaxactordao::countCorporateByCompanyIdAndTaxCode;
break;
}
case CORPORATE: {
findById = customerService::findTaxCodeAndDisabledById;
existsCounter = individualTaxactordao::countIndividualByCompanyIdAndTaxCode;
break;
}
default:
throw new RuntimeException("不能识别的个税客户类型:" + type);
}
IdAndTaxCodeAndDisabledOnly customer = findById.apply(customerId);
if (customer == null) {
throw new ApplicationRuntimeException(HttpStatus.NOT_FOUND,"客户不存在");
}
if(customer.isDisabled()){
throw new ApplicationRuntimeException(HttpStatus.FAILED_DEPENDENCY,"客户已禁用");
}
int exists=existsCounter.apply(principal.getcompanyid(),customerId);
if(exists>0){
throw new ApplicationRuntimeException(HttpStatus.CONFLICT,"已是智能个税客户,不可重复添加。");
}
// insert into table ... ignore for conciseness
}
绝对重复的代码片段行是:
在search
方法中:
switch (type) {
case INDIVIDUAL: {
counter = individualTaxactordao::countIndividual;
searcher = individualTaxactordao::searchIndividual;
break;
}
case CORPORATE: {
counter = individualTaxactordao::countCorporate;
searcher = individualTaxactordao::searchCorporate;
break;
}
default:
throw new RuntimeException("不能识别的个税客户类型:" + type);
}
并使用link
方法:
switch (type){
case INDIVIDUAL: {
findById = individualCustomerService::findTaxCodeAndDisabledById;
existsCounter = individualTaxactordao::countCorporateByCompanyIdAndTaxCode;
break;
}
case CORPORATE: {
findById = customerService::findTaxCodeAndDisabledById;
existsCounter = individualTaxactordao::countIndividualByCompanyIdAndTaxCode;
break;
}
default:
throw new RuntimeException("不能识别的个税客户类型:" + type);
}
我认为这两个代码段具有绝对不同的逻辑,但具有相同的switch
模式,我无法忍受IDE警告,请帮助我修复它。