2

I use tool to check coding style and I got hundreds of this advise :

Local variable 'XXX' could be declared final

Here is some of my code:

//Local variable 'cookies' could be declared final    
Cookie[] cookies = request.getCookies();

//Local variable 'cookie' could be declared final
if (cookies != null) {

  for (Cookie cookie : cookies) {
  }
}

//Local variable 'qry' could be declared final
StringBuffer qry = new StringBuffer("from User u where u.account=? ");

Is it means I should use final like

 final Cookie[] cookies = request.getCookies();
user2492364
  • 6,543
  • 22
  • 77
  • 147

3 Answers3

1

It is suggesting that because you do not change cookies in this example (after the first call to getCookies(), that it should be declared final.

I would listen to the warning. If that is what you want, final offers an additional protection against the program (or you) trying to write to cookies if you shouldn't be.

Lawrence Aiello
  • 4,560
  • 5
  • 21
  • 35
0

First You should understand the advantages of Final. If we declare any variable as a final variable then that variable we cannot reinitialize it again and again. I guess, In your code those variables are Initialize once and using many times. That's why tool suggest to declare that variable as a final variable.

Final variables --- Initializing once and using many times.

0

You are right.

It is a good practice to declare variables, who won't have their value changed during the execution of the program as final. This will help you detect invalid operations (changing the value) on the variable at compile time and prevent some nasty bugs from creeping into your codebase. This is why many code style tools highlight such variables in the code and suggest they are declared as final.

Danail Alexiev
  • 7,624
  • 3
  • 20
  • 28