Sonar complaining about useless assignment of loca

2019-07-25 03:51发布

问题:

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.