代码规范类问题修改方法

问题描述:Define a constant instead of duplicating this literal “total” 3(表示一个字符串重复出现了3次)
解决方法:将多次重复使用的字符串定义成一个字符串常量,使用时直接调用定义的字符串常量

private static final String TOTAL = "total";

问题描述:Either log or rethrow this exception
解决方法:catch语句中不能为空,添加一些代码,当使用logger打印出日志时,需要传递两个参数,且第二个参数值为e
修改前的代码

try {
    return address.isReachable(100);
} catch (IOException e) {
}

修改后的代码

try {
    return address.isReachable(100);
} catch (IOException e) {
    logger.error(e.getMessage(), e);
}

问题描述:Replace this usage of Sun classes by ones from the Java
解决方法:删除无用的jar包

问题描述:Move constants to a class or enum
解决方法:常量不应定义在一个接口中,常量可以定义在使用该常量的类中
修改前的代码:将常量定义在一个接口中,当需要使用常量时,直接调用接口中定义好的常量

public interface HomePageConstant {
    String VALUE="value";
    String WARN_LEVEL="warnLevel";
    String WARN_LEVEL_STR="warnlevelstr";
    String COUNT="count";
    String ERROR="error";
    String FATAL="fatal";
    String DEVICE_TYPE="devicetype";
    String NAME="name";
    String SKIN = "\\skin.json";
    String DEFAULTP = "defaultp";
    String DEFAULTP_VALUE="60ab0514021d5549";
    int TIME = 1000000000;
}

修改后的代码: 当有类需要定义常量时,直接在类中定义常量,而不是在接口中定义常量

@Controller
@RequestMapping(value = "homepage")
public class HomepageController extends BaseController {

    private static final Logger logger = Logger.getLogger(HomepageController.class);
    private static final String VALUE = "value";
    private static final String WARN_LEVEL = "warnLevel";
    private static final String WARN_LEVEL_STR = "warnlevelstr";
    private static final String COUNT = "count";
    private static final String INFO = "info";
    private static final String WARN = "warn";
    private static final String ERROR = "error";
    private static final String FATAL = "fatal";
    private static final String DEVICE_TYPE = "devicetype";
    private static final String NAME = "name";
    private static final String SKIN = File.separator + "skin.json";
    private static final String DEFAULTP = "defaultp";
    private static final String DEFAULTP_VALUE = "60ab0514021d5549";
    private static final int TIME = 1000000000;
}

问题描述:Replace this usage of System.out or System.err by a
解决方法:删掉日志打印语句

问题描述:Return an empty array instead of null
解决方法:将null改成空数组

问题描述:Remove this unused method parameter “isAjax“
解决方法:删除无用的函数参数isAjax
修改前的代码:isAjax作为函数的参数,没有在函数内部使用

private boolean renderError(HttpServletRequest request, HttpServletResponse response, boolean isAjax) throws IOException {
    csrfTokenRepository.saveToken(null, request, response);
    PrintWriter p = response.getWriter();
    p.write("不能重复提交数据");
    p.flush();
    p.close();
    return false;
}

修改后的代码

private boolean renderError(HttpServletRequest request, HttpServletResponse response) throws IOException {
    csrfTokenRepository.saveToken(null, request, response);
    PrintWriter p = response.getWriter();
    p.write("不能重复提交数据");
    p.flush();
    p.close();
    return false;
}

问题描述:4 duplicated blocks of code must be removed(表示代码中有4处重复代码块)
解决方法:首先使用idea自带的Locate Duplicates工具检测重复代码块出现的位置,然后优化代码的实现逻辑,解决重复代码块类问题
优化前的代码

@ResponseBody
@RequestMapping("/getResourceStatus")
public Map<String, Object> getResourceStatus(long userId, long resType) {

    Map<String, Object> info = null;
    Map<String, Object> warn = null;
    Map<String, Object> error = null;
    Map<String, Object> fatal = null;
    long infoCount ;
    long warnCount ;
    long errorCount ;
    long fatalCount ;

    if (resType == 1) {
        info = service.getOracleStatus(userId, 1);
        warn = service.getOracleStatus(userId, 2);
        error = service.getOracleStatus(userId, 3);
        fatal = service.getOracleStatus(userId, 4);

    } else if (resType == 2) {
        info = service.getSgrdbStatus(userId, 1);
        warn = service.getSgrdbStatus(userId, 2);
        error = service.getSgrdbStatus(userId, 3);
        fatal = service.getSgrdbStatus(userId, 4);

    } else if (resType == 3) {
        info = service.getNbaseStatus(userId, 1);
        warn = service.getNbaseStatus(userId, 2);
        error = service.getNbaseStatus(userId, 3);
        fatal = service.getNbaseStatus(userId, 4);
    }

    if (info != null) {
        infoCount = (long)getFirstOrNull(info);
    } else {
        infoCount = 0;
    }

    if (warn != null) {
        warnCount = (long)getFirstOrNull(warn);
    } else {
        warnCount = 0;
    }

    if (error != null) {
        errorCount = (long)getFirstOrNull(error);
    } else {
        errorCount = 0;
    }

    if (fatal != null) {
        fatalCount = (long)getFirstOrNull(fatal);
    } else {
        fatalCount = 0;
    }

    JSONObject infoJson = new JSONObject();
    infoJson.put(WARN_LEVEL, 1);
    infoJson.put(WARN_LEVEL_STR, "信息");
    infoJson.put(COUNT, infoCount);

    JSONObject warnJson = new JSONObject();
    warnJson.put(WARN_LEVEL, 2);
    warnJson.put(WARN_LEVEL_STR, "警告");
    warnJson.put(COUNT, warnCount);

    JSONObject errorJson = new JSONObject();
    errorJson.put(WARN_LEVEL, 3);
    errorJson.put(WARN_LEVEL_STR, "错误");
    errorJson.put(COUNT, errorCount);

    JSONObject fatalJson = new JSONObject();
    fatalJson.put(WARN_LEVEL, 4);
    fatalJson.put(WARN_LEVEL_STR, "致命");
    fatalJson.put(COUNT, fatalCount);

    Map<String, Object> map = new HashMap<String, Object>();
    map.put(INFO, infoJson);
    map.put(WARN, warnJson);
    map.put(ERROR, errorJson);
    map.put(FATAL, fatalJson);

    return map;
}

优化后的代码

@ResponseBody
@RequestMapping("/getResourceStatus")
public Map<String, Object> getResourceStatus(long userId, long resType) {

    Map<String, Object> warnObj = null;
    Map<String, Object> map = new HashMap<String, Object>();
    int[] warnNo = {1, 2, 3, 4};
    String[] warnText = {"信息", "警告", "错误", "致命"};
    String[] warnStr = {INFO, WARN, ERROR, FATAL};

    for (int warnLevel = 1; warnLevel <= 4; warnLevel++) {

        if (resType == 1) {
            warnObj = service.getOracleStatus(userId, warnLevel);

        } else if (resType == 2) {
            warnObj = service.getSgrdbStatus(userId, warnLevel);

        } else if (resType == 3) {
            warnObj = service.getNbaseStatus(userId, warnLevel);
        }

        JSONObject warnJson = new JSONObject();
        warnJson.put(WARN_LEVEL, warnNo[warnLevel - 1]);
        warnJson.put(WARN_LEVEL_STR, warnText[warnLevel - 1]);
        warnJson.put(COUNT, warnObj != null ? (long)getFirstOrNull(warnObj) : 0);
        map.put(warnStr[warnLevel - 1], warnJson);
    }

    return map;
}

问题描述:Refactor this method to reduce its Cognitive Complexity(重构此方法以降低其认知复杂性)
解决方法:将一个比较复杂的方法拆分成多个方法
修改前的代码

private List<Param> initParams(Map<String, Object> mapConfig) {
    List<Param> globalParams = Lists.newArrayList();
    if (mapConfig.get(ResConfigParam.IS_AUTOMATIC_MEMORY) != null) {
        Param param = new Param();
        param.setParamId("90011");
        param.setParamValue((String) mapConfig.get(ResConfigParam.IS_AUTOMATIC_MEMORY));
        globalParams.add(param);
    } else if ("1".equals(mapConfig.get(ResConfigParam.IS_AUTOMATIC_MEMORY))) {
        if (mapConfig.get(ResConfigParam.MEMORY_TARGET) != null) {
            Param param = new Param();
            param.setParamId("90014");
            param.setParamValue((String) mapConfig.get(ResConfigParam.MEMORY_TARGET));
            globalParams.add(param);
        }
    } else {
        if (mapConfig.get(ResConfigParam.SGA_MAX_SIZE) != null) {
            Param param = new Param();
            param.setParamId("90015");
            param.setParamValue((String) mapConfig.get(ResConfigParam.SGA_MAX_SIZE));
            globalParams.add(param);
        } else if (mapConfig.get(ResConfigParam.PGA_AGGERGATE_LIMIT) != null) {
            Param param = new Param();
            param.setParamId("90016");
            param.setParamValue((String) mapConfig.get(ResConfigParam.PGA_AGGERGATE_LIMIT));
            globalParams.add(param);
        }
    }
    return globalParams;
}

修改后的代码

private List<Param> initParams(Map<String, Object> mapConfig) {
    List<Param> globalParams = Lists.newArrayList();
    if (mapConfig.get(ResConfigParam.IS_AUTOMATIC_MEMORY) != null) {
        Param param = new Param();
        param.setParamId("90011");
        param.setParamValue((String) mapConfig.get(ResConfigParam.IS_AUTOMATIC_MEMORY));
        globalParams.add(param);
    } else if ("1".equals(mapConfig.get(ResConfigParam.IS_AUTOMATIC_MEMORY))) {
        if (mapConfig.get(ResConfigParam.MEMORY_TARGET) != null) {
            Param param = new Param();
            param.setParamId("90014");
            param.setParamValue((String) mapConfig.get(ResConfigParam.MEMORY_TARGET));
            globalParams.add(param);
        }
    } else {
        globalParams.addAll(createGlobalParams(mapConfig));
    }
    return globalParams;
}

public List<Param> createGlobalParams(Map<String, Object> mapConfig) {
    List<Param> globalParams = Lists.newArrayList();
    if (mapConfig.get(ResConfigParam.SGA_MAX_SIZE) != null) {
        Param param = new Param();
        param.setParamId("90015");
        param.setParamValue((String) mapConfig.get(ResConfigParam.SGA_MAX_SIZE));
        globalParams.add(param);
    } else if (mapConfig.get(ResConfigParam.INMEMORY_SIZE) != null) {
        Param param = new Param();
        param.setParamId("90020");
        param.setParamValue((String) mapConfig.get(ResConfigParam.INMEMORY_SIZE));
        globalParams.add(param);
    }

    return globalParams;
}

问题描述:Reduce the number of conditional operators (7) used in(减少运算符的使用数量)
解决方法:将运算符语句拆分成多个方法

修改前的代码

private boolean hasPermission(User user,String url,String perUrl){

    return !user.getPermissions().contains(perUrl)
            && !perUrl.equals("jsp/")
            && url.indexOf("login")<0
            && !perUrl.equals("jsp/comm/jsp/")
            && !perUrl.equals("jsp/plugins/")
            && !perUrl.equals("jsp/comm/")
            && !perUrl.equals("jsp/pages/")
            && !url.endsWith("modifyPass.jsp");
}

修改后的代码

private boolean hasPermission(User user, String url, String perUrl) {
    return ischeckUrl(user, url, perUrl) && isCheck(url, perUrl);
}

public boolean ischeckUrl(User user, String url, String perUrl) {
    return  !user.getPermissions().contains(perUrl)
            && !perUrl.equals("jsp/")
            && url.indexOf("login") < 0
            && !perUrl.equals("jsp/comm/jsp/");
}

public boolean isCheck(String url, String perUrl) {
    return  !perUrl.equals("jsp/plugins/")
            && !perUrl.equals("jsp/comm/")
            && !perUrl.equals("jsp/pages/")
            && !url.endsWith("modifyPass.jsp");
}

问题描述:Refactor this code to not nest more than 3(代码嵌套层级超过了3层)
解决方法:重构代码,降低代码嵌套层级
修改前的代码

public Map<String, Object> findAllCluster(ClusterPo po, HttpServletRequest request, HttpServletResponse response) {
    Page<ClusterPo> page = clusterService.findResAllCluster(new Page<ClusterPo>(request, response), po.getResourceId());
    List<ClusterPo> clusterList = clusterService.findAllClusterId(po.getWorkform_id());
    if(clusterList!=null && clusterList.size()>0){
        for (ClusterPo cluster : page.getList()) {
            for(ClusterPo selecteds: clusterList){
                if(selecteds.getClusterId().contains(cluster.getClusterId())){
                    cluster.LAY_CHECKED=true;
                }
            }

        }
    }
    return R.ok().setPage(page);
}

修改后的代码

public Map<String, Object> findAllCluster(ClusterPo po, HttpServletRequest request, HttpServletResponse response) {
    Page<ClusterPo> page = clusterService.findResAllCluster(new Page<ClusterPo>(request, response), po.getResourceId());
    List<ClusterPo> clusterList = clusterService.findAllClusterId(po.getWorkform_id());

    if (clusterList == null || clusterList.size() <= 0) {
        return R.ok().setPage(page);
    }

    for (ClusterPo cluster : page.getList()) {
        for(ClusterPo selecteds: clusterList){
            if(selecteds.getClusterId().contains(cluster.getClusterId())){
                cluster.LAY_CHECKED=true;
            }
        }
    }

    return R.ok().setPage(page);
}

问题描述:Change this “try” to a try-with-resource
解决方法:使用try-with-resource代替try-catch
参考资料:java 7 新特性 try-with-resources
修改前的代码

BufferedReader in = null;
InputStreamReader isr=null;
try{
    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost();
    request.setURI(new URI(url));
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
        String name = (String) iter.next();
        String value = String.valueOf(params.get(name));
        nvps.add(new BasicNameValuePair(name, value));
    }
    request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    HttpResponse response = client.execute(request);
    int code = response.getStatusLine().getStatusCode();
    if(code == 200){    //请求成功
        isr=new InputStreamReader(response.getEntity().getContent(),"utf-8");
        in = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder("");
        String line = in.readLine();
        String NL = System.getProperty("line.separator");
        while (line != null) {
            sb.append(line + NL);
        }
        return sb.toString();
    }
    else{
        return null;
    }
}catch(Exception e){
    logger.error(e.getMessage(),e);
    return null;
}finally {
    if(in!=null){
        try {
            in.close();
        }catch(IOException ioe){
            logger.error("BufferedReader close error "+ioe.getMessage(),ioe);
        }
    }
    if(isr!=null){
        try {
            isr.close();
        }catch(IOException ioe){
            logger.error("InputStreamReader close error "+ioe.getMessage(),ioe);
        }
    }
}

修改后的代码

try (
        InputStreamReader isr = new InputStreamReader(response.getEntity().getContent(), "utf-8");
        BufferedReader in = new BufferedReader(isr);
) {
    StringBuilder sb = new StringBuilder("");
    String line = in.readLine();
    String NL = System.getProperty("line.separator");
    while (line != null) {
        sb.append(line + NL);
    }
    return sb.toString();
} catch (Exception e) {
    logger.error(e.getMessage(), e);
    return null;
}

问题描述:Remove this unused private “initInstanceNodeTree”
解决方法:将私有方法改成公有方法
修改前的代码

private void initInstanceNodeTree(List<Map<String, Object>> mapList, ClusterPo clusterPo, int i,int deleted) {
}

修改后的代码

public void initInstanceNodeTree(List<Map<String, Object>> mapList, ClusterPo clusterPo, int i,int deleted) {
}

问题描述:This block of commented-out lines of code should be
解决方法:去掉代码注释
参考资料:sonar常见错误以及处理方案

问题描述:Add a private constructor to hide the implicit public one
解决方法:给静态类添加一个私有构造函数
参考资料:add a private constructor to hide the implicit public one
修改前的代码

public class Digests {
}

修改后的代码

public class Digests {

    private Digests() {
    }
}

问题描述:Rename “orderBy” which hides the field declared at line(重命名“orderBy”,隐藏在行声明的字段,ordyBy即是Page类的成员变量,有时构造函数的局部变量容易引起歧义)
解决方法:重命名构造函数中的局部变量orderBy
参考资料:Sonar
修改前的代码

public class Page<T> {

    private String orderBy = "";

    public Page(HttpServletRequest request){

        String orderBy = request.getParameter("orderBy");
        if (StringUtils.isNotBlank(orderBy)){
            this.setOrderBy(" " + orderBy + " ");
        }
    }
}

修改后的代码

public class Page<T> {

    private String orderBy = "";

    public Page(HttpServletRequest request){

        String orderByParam = request.getParameter("orderBy");
        if (StringUtils.isNotBlank(orderByParam)){
            this.setOrderBy(" " + orderByParam + " ");
        }
    }
}

问题描述:Iterate over the “entrySet” instead of the “keySet”(迭代使用“entrySet”而不是“keySet”)
解决方法:使用 entrySet 代替 KeySet
修改前的代码

public Map<String,String[]> getParameterMap() {
    Map<String,String[]> map = new LinkedHashMap<>();
    Map<String,String[]> parameters = super.getParameterMap();
    for (String key : parameters.keySet()) {
        String[] values = parameters.get(key);
        for (int i = 0; i < values.length; i++) {
            values[i] = xssEncode(values[i]);
        }
        map.put(key, values);
    }
    return map;
}

修改后的代码

public Map<String,String[]> getParameterMap() {
    Map<String,String[]> map = new LinkedHashMap<>();
    Map<String,String[]> parameters = super.getParameterMap();
    for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
        String[] values = entry.getValue();
        for (int i = 0; i < values.length; i++) {
            values[i] = xssEncode(values[i]);
        }
        map.put(entry.getKey(), values);
    }
    return map;
}

meishadevs欢迎任何形式的转载,但请务必注明出处,尊重他人劳动成果。
转载请注明: 【文章转载自meishadevs:代码规范类问题修改方法

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器