for(Deductible **myDeductible**: myDeductibles){
myReturnList.add(myOption); // Add options as many times as number of deductibles
if(CoverageConstants.COVERAGE_CODE_VC.equalsIgnoreCase(aCoverage.getCoverageCd()) &&
!CoverageConstants.OPTION_CODE_ONE.equals(myOption.getOptionCd())){
break;
}
}
uppder代码如何修复未使用的局部变量myDeductible。请给出建议。
答案 0 :(得分:0)
而不是for(Deductible myDeductible: myDeductibles){
使用旧式循环:
for(int count = 0; count < myDeductibles.size(); count++) {
答案 1 :(得分:0)
PMD让您知道您正在分配但不使用myDeductible
,即有一些可疑的东西正在进行中。
查看您提供的代码段,我们可以看到多个输入(myDeductibles
,myOption
和aCoverage
)和一个输出(myReturnList
)。此外,还有一个循环用myReturnList
填充myOption
和一个打破循环的条件。
仔细观察条件告诉我们,在循环内,条件总是true
或始终false
,假设吸气剂没有副作用并且返回始终相同。
由此我们可以推断,一旦循环完成myReturnList
只能有三种状态中的一种:
myDeductibles
为空时myReturnList
为空myDeductibles
不为空并且条件为true
时,myReturnList
只包含一个myOption
,因为条件在添加第一个myOption
后会中断循环myDeductibles
不为空并且条件为false
时,myReturnList
包含与myOption
您可能已经注意到,上述三个结果中没有一个取决于myDeductibles
本身的元素,仅取决于元素的数量。这就是PMD试图告诉我们的。
现在我们知道循环实际上在做什么,我们可以通过实现三个结果而不使用myDeductibles
的元素来修复警告:
List<Option> myReturnList;
if (myDeductibles.isEmpty()) {
myReturnList = Collections.emptyList();
} else if (CoverageConstants.COVERAGE_CODE_VC.equalsIgnoreCase(aCoverage.getCoverageCd())
&& !CoverageConstants.OPTION_CODE_ONE.equals(myOption.getOptionCd())) {
myReturnList = Collections.singletonList(myOption);
} else {
myReturnList = Collections.nCopies(myDeductibles.size(), myOption);
}