记录安全扫描后进行的代码重构各种问题以及处理办法

项目由于是政府的项目,须要对代码进行安全扫描,花了点时间对代码进行重构,因此对问题作下记录,你们有更好的解决办法欢迎指出,会随时进行补充问题java

1Either log or rethrow this exception.(日志或从新抛出此异常。express

处理方式:在catch中加上打印日志设计模式

          logger.error("添加的说明信息 ",e);安全

2Remove this useless assignment to local variable "XXX".(删除这个无用的赋值到局部变量“XXX”)session

处理方式:将这两段代码合并为一列 List<String> timelist = getTimeList();less

3This block of commented-out lines of code should be removed.(删除这段注释掉的代码块)工具

处理方式:直接将注释的代码删除ui

4Define a constant instead of duplicating this literal "repeatData" 3 times.(定义一个常量,而不是重复这个“repeatData”3次。this

例子:在一个类里面屡次使用了同样的字符串文本spa

处理方式:定义类常量或者枚举类或者接口常量类,用常量来代替重复的文本

5duplicated blocks of code must be removed.(必须删除重复的代码块。)

这类问题在代码重构是碰到最多的

处理方式:抽取重复的代码块做为一个共用的方法或者抽取工具类方法

6Refactor this code to not nest more than 3 if/for/while/switch/try statements.(重构此代码以不嵌套超过3 if/for/while/switch/try语句。)

这也是最多见的问题 嵌套if for过多

解决办法:1抽取方法,

                2.使用设计模式

                3. 采用卫语句

7.Refactor this method to reduce its Cognitive Complexity from 48 to the 15 allowed.(重构这种方法,将其认知复杂性从48下降到15。)

表示一个方法行数不少比较复杂,一样的解决办法就是抽取方法,讲一个方法拆分几个方法

8.Method has 9 parameters, which is greater than 7 authorized.(方法有9个参数,大于7个受权参数。)

一个方法参数过多,解决办法封装成对象或者map

9Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".(将同步类“StringBuffer”替换为非同步类,例如“StringBuilder”。)

其实若是用StringBuffer时 jdk也会进行锁消除的

10Refactor this method to throw at most one checked exception instead of: java.lang.NoSuchMethodException, java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException(重构此方法以抛出最多一个检查异常)

解决办法:自定义运行时异常,或者抛出更大的异常

11NullPointerException might be thrown as 'session' is nullable here(可能会抛出NullPointerException,由于“session”在这里是可空的)

处理方式:加一个非空判断

12Close this "InputStreamReader".(关闭这个“InputStreamReader”。)

输入输出流在finally中进行关闭

13、Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.(添加一个嵌套注释,解释为何这个方法是空的,抛出UnsupportedOperationException,或者完成这个实现。)

处理方式:由于不须要实现这个方法因此直接添加注释解释一下

14Make "modelparam" transient or serializable.

 

顶层接口对象或者抽象类的引用是没有实现序列化接口的,因此实体实现了系列化的时候,这些顶层接口的引用编译时没法肯定类型

解决方法:

  1. 使用实现了序列化接口的子类
  2. 使用transient关键字表示不序列化该字段

15Reduce the number of conditional operators (7) used in the expression (maximum allowed 3).

一个if的条件表达式过多问题

解决办法提取表达式成为一个方法

变动前:

变动后:

相关文章
相关标签/搜索