[java] How to understand "AvoidFinalLocalVariable" and "LocalVariableCouldBeFinal" #3043
-
The rule "AvoidFinalLocalVariable" says: Avoid using final local variables, turn them into fields. And the rule "LocalVariableCouldBeFinal" says: A local variable assigned only once can be declared final. It seems that they go against each other. The result of the two rules above is that all the local variables which assigned once turn into fields. I know that final variable can improve performance. But what's the difference between a local variable and a field? Why should I turn local variable to field? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
@lonelyma1021 these are separate rules. It's up to each user to decide if they apply to their projects or not (and if both are required!).
This last one is, in my opinion, the strongest reason to adopt this rule. Reassigning parameters / local variables means that knowing the actual value they have at a single point requires looking at the whole code between declaration and that point, taking into account all plausible execution paths (which corresponds to cyclomatic complexity). If variables are final, you only have to look for it's initialization, and be safe the value will be that. Most often than not, if you are reassigning a variable it's either:
As for |
Beta Was this translation helpful? Give feedback.
@lonelyma1021 these are separate rules. It's up to each user to decide if they apply to their projects or not (and if both are required!).
LocalVariableCouldBeFinal
attempts to flag local variables as finals. This has 2 main purposes:This last one is, in my opinion, the strongest reason to adopt this rule.
Reassigning parameters / local variables means that knowing the actual value they have at a single point requires looking at the whole code between declaration and that point, taking into account all plausible execution paths (which corresponds to cyclomatic complexity).
If variables are final, you only have to look fo…