Sonar complaining about useless assignment of local variable

烂漫一生 提交于 2019-12-11 04:49:25

问题


I have the following piece of code in my program and I am running SonarQube 5 for code quality check on it after integrating it with Maven.

However, Sonar is asking to Remove this useless assignment to local variable "session".

@RequestMapping(value = "/logoff", method = RequestMethod.GET)
public String getLogoffPage(HttpServletRequest request, HttpServletResponse response) {
    logger.info(" Before Log Offf........ " + request.getSession().getId() );
    HttpSession session =request.getSession(true);
    request.getSession().invalidate();
    myApplication.logout();
    SecurityContextHolder.clearContext();
    session=null;                   
    return "login";
}

回答1:


Under the assumption that the question is "why":

What do you actually do with session? Nothing.

HttpSession session =request.getSession(true);  // session assigned
request.getSession().invalidate();         // session NOT used
myApplication.logout();
SecurityContextHolder.clearContext();
session=null;                            // session re-assigned

Perhaps you meant this?

HttpSession session =request.getSession(true);
session.invalidate();
myApplication.logout();
SecurityContextHolder.clearContext();

BTW, I've dropped session = null since there's no reason in Java (C would be another matter) to do that.

Of course, the code could be even cleaner:

request.getSession().invalidate();
myApplication.logout();
SecurityContextHolder.clearContext();



回答2:


This variable is local and so when you reach the return statement it won't be accessible. As it is not read after the assignement the variable is considered Dead.

If you assign anything to a local variable and do not make use of it this is a useless instruction and thus should be removed.

Setting the variable to null is pretty much useless and in fact may be preventing the JVM to work on some optimization.



来源:https://stackoverflow.com/questions/39342828/sonar-complaining-about-useless-assignment-of-local-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!