目录
1. Refactor this loop to do more than one iteration.
3. Remove this useless assignment to variable "n".
4. This branch duplicates the one on line 210
5. Remove this conditional structure or edit its code blocks so that they're not all the same.
7. Correct one of the identical sub-expressions on both sides of operator "&&"
8. This conditional operation returns the same value whether the condition is "true" or "false".
9. Remove this use of the output from "dedent"; "dedent" doesn't return anything.
10. Remove this "!==" check; it will always be true. Did you mean to use "!="?
如果是首次阅读,推荐结合上一篇文章一起看。《Sonar 代码检测常见问题及修改实例(前端JS版本)》,
1. Refactor this loop to do more than one iteration.
问题代码:
解决
去掉第一层关于变量 j 的外循环,因为它确实毫无意义。程序执行完内循环,代码就 return 退出了,不会再执行外层循环。因此,去掉关于变量 j 的外循环即可。
2. Duplicate key '*'.
问题实例:Duplicate key 'zIndex'.
其实上一篇文章已经介绍过这个问题了,但是这次为什么还拿出来说呢,因为这个实例和上次的确实有所不同。
解决
如上图所示,定义了相同属性 zIndex 两次,那么问题来了,到底是赋值 100 生效,还是赋值 101 生效呢?实际上是后面的属性设置生效了,也就是 100,因为前面的设置被覆盖了。因此,我们只能去掉首次的属性设置,才不会影响代码的原有逻辑。
3. Remove this useless assignment to variable "n".
问题代码:
解决
n-- 最终作用到变量 m 和变量 n 上,前者还有意义,后边还会用到,但是后者之后就再也没有被使用了。因此,改成 m=n-1 即可。
4. This branch duplicates the one on line 210
问题代码:
解决
去掉相同的条件判断分支即可。
5. Remove this conditional structure or edit its code blocks so that they're not all the same.
问题代码:
解决
if 和 else 的路径逻辑一样,因此,完全没有必要进行判断,直接使用 source.next() 即可。
6. '*' is assigned to itself.
问题实例:'state.next' is assigned to itself.
问题代码:
解决
去掉该语句即可。
7. Correct one of the identical sub-expressions on both sides of operator "&&"
问题代码:
解决
相同表达式保留一个即可。
8. This conditional operation returns the same value whether the condition is "true" or "false".
解决
修改返回值或者去掉判断逻辑。
9. Remove this use of the output from "dedent"; "dedent" doesn't return anything.
问题代码:
解决
为 dedent 方法增加返回值或者去掉返回值的引用逻辑。如上图代码所示,由于 dedent 方法没有返回值,程序永远不会执行 if 判断中的 return 语句。
10. Remove this "!==" check; it will always be true. Did you mean to use "!="?
问题代码:
解决
== 和 != 比较时,如果类型不同,会先尝试转换类型,再作值比较,最后返回比较的结果 。
=== 和 !== 比较时,只有在相同类型下,才会比较其值。如果前后类型不同,则永远返回 (===)false 和 (!==)true。
因此,根据代码的原有逻辑,应该修改为 != 。