如何解决Sonarqube将多个if return语句判定为重复代码的问题
问题原因
Sonarqube的重复代码检测识别的是结构化重复逻辑,你原来的代码里多段if(阈值判断) 返回对应值的代码结构完全一致,不管是把return替换为变量赋值,还是删掉else语句,都没有改变这种重复的结构模式,因此不会消除重复代码告警。
解决方案
你可以把阈值和对应的返回值抽象为有序映射表,通过遍历查表的方式替换多分支if判断,完全消除结构重复:
private static double computeGain(int rangeMax) { // 按阈值从小到大排列的 阈值-增益 映射 int[] thresholds = {35, 85, 170, 340, 850, 1700, 3400, 8000}; double[] gains = {6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.5, 0.25}; for (int i = 0; i < thresholds.length; i++) { if (rangeMax <= thresholds[i]) { return gains[i]; } } return 0.0D; }
如果使用Java 8及以上版本,也可以用TreeMap的内置方法实现更简洁的查表逻辑,语义更清晰:
private static final NavigableMap<Integer, Double> GAIN_MAP = new TreeMap<>(); static { GAIN_MAP.put(35, 6.0); GAIN_MAP.put(85, 5.0); GAIN_MAP.put(170, 4.0); GAIN_MAP.put(340, 3.0); GAIN_MAP.put(850, 2.0); GAIN_MAP.put(1700, 1.0); GAIN_MAP.put(3400, 0.5); GAIN_MAP.put(8000, 0.25); } private static double computeGain(int rangeMax) { Map.Entry<Integer, Double> entry = GAIN_MAP.ceilingEntry(rangeMax); return entry != null ? entry.getValue() : 0.0D; }
两种方案都完全消除了重复的if分支结构,不会再触发Sonarqube的重复代码告警,同时后续如果要调整阈值和增益,只需要修改映射表即可,可维护性也比多分支if更高。
内容的提问来源于stack exchange,提问作者jfpatenaude
相关产品推荐
相关产品推荐

