This question already has answers here:
When should one use final for method parameters and local variables?
(15 answers)
Closed 10 years ago.
I use PMD tool to find errors in java code if any. One common suggestion PMD gives is that "Local variable {local_variable} could be declared final". Is it necessary to declare all local variables as final if it's state is not changed further?
Is it necessary to declare all local variables as final if it's state is not changed further?
No it is not necessary, except in one situation: if you need to access that variable within an anonymous class.
Is it good practice to make all local variable final when they don't change?
This is obviously subjective - I personally think that it clutters the code unnecessarily and that if you follow good coding practice, your methods should be short enough and self-explanatory enough that making your variables final should not be required.
Well it's also a problem of the language design to set variables explicitly to final and to have the final keyword appear all around. In scala the default is to have everything final and immutable, pushing a more functional design. If you wonder why use final, have a look at scala - that should give you some ideas.
I would consider it bad style not to use final by the way. Final variables - well or constants in that sense - cannot be changed. That is kind of a programming contract. You simply have less side-effects in code with final variables. If you leave that out you could also leave out all the private fields. Why bother?
In eclipse you can add all the required final fields and lots of other things considered "cleaner" automatically, when you open the dialog "Source/Clean Up..." (so I guess it's called "Clean Up" because not using final would be considered unclean).
It's up to you - use it - or leave it. Use it - and look especially at the code where the final could not be applied. Maybe that code could be improved to be final?
So: Yes! It is good practice!
Related
This question already has answers here:
Why must local variables, including primitives, always be initialized in Java?
(8 answers)
Closed 6 years ago.
In JAVA world, field variables have default values if you don't initialize them, while local variables don't.
I have considered a lot and searched a lot but I still don't understand. Why does JAVA world design like that? By the way, I think it has something to do with heap and stack.
Local variables are much easier to check that a variable is always initialised in a relatively limited scope when you can determine the code paths. It doesn't always get it right but does a good job unless the code is confusing.
final fields also have to be initialised, though only once. When one constructor calls another, it can get confused.
For non final fields, it is very hard to ensure a field is initialised before it is used for all possible code paths. e.g. how can it ensure a setter is always called before a getter if those calls are made from another class which might be changed in the future.
Instead the JVM leaves default values and makes it your problem to worry about.
Well, it is very good design in my opinion.
The compiler is trying to check if programmer did not make any mistakes. Local variable should be initialized manually to avoid unexpected problems because it is usually used to do some additional calculations or actions and with default value it can be very difficult to track such a bug in the future. It is programmer responsibility to initialize local variable properly and use it in short block of code.
This question already has answers here:
Does use of final keyword in Java improve the performance?
(14 answers)
Closed 7 years ago.
Now, I recently ran into a recommendation that you should use the keyword final as wide as possible. This is good in order to prevent a programmer from shooting his own leg - that is, reassign the variable that should not be reassigned.
But, does it serve any other goal? That is, can JVM use information about the final variables in order to optimize the bytecode somehow, so it would ran faster (build a better pipelining or use it in a multithreaded environment)? Or is just a syntactic sugar that minimizes the possibility of errors during code development?
IBM states:
Like many myths about Java performance, the erroneous belief that declaring classes or methods as final results in better performance is widely held but rarely examined. The argument goes that declaring a method or class as final means that the compiler can inline method calls more aggressively, because it knows that at run time this is definitely the version of the method that's going to be called. But this is simply not true. Just because class X is compiled against final class Y doesn't mean that the same version of class Y will be loaded at run time. So the compiler cannot inline such cross-class method calls safely, final or not. Only if a method is private can the compiler inline it freely, and in that case, the final keyword would be redundant.
As far as variables go, Java is smart enough to figure that a variable is not being changed anywhere in the method, and use this knowledge for optimization purposes. It does not need you to mark a variable final in order to know that.
Methods are a slightly different story: when you mark a method final, Java can invoke such method faster, because it no longer needs to check for its overrides. Still, hotspot is smart enough to figure out that there are no overrides, with or without the use of final.
Generally, though, this recommendation is intended to make your code easier to read and understand by others: making a variable final tells you readers that you are making a constant; making a class final tells your readers that the class is not designed for inheritance; making a method final tells your readers that the logic of that method should stay invariant across the inheritance hierarchy. In the long run, this information is more valuable than the potential to optimize your running code.
I think this recommendation is a bit too unspecific.
For example; I would recommend to avoid using final on classes and methods by default (because final classes break unit tests, respectively force you to use specific unit test frameworks to overcome final methods/classes).
I also find that using final for method parameters is just a waste of "screen space" (and thus: wasting "energy" on the side of the reader).
On the other hand, having only final attributes for classes can turn objects of such classes into immutable thingies; and that is a good thing.
As you see; there are many pros and cons on the usage of final; and I think that "readability" most often wins over "potential" performance improvements.
final methods may or may not be inlined by the JVM until they after they are loaded by the JVM. So, if you're sure the method is not going to be redefined, mark it as final.
Constants should always be static final since they will be immutable and jvm does not need to keep track of these variables since they will never change.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there any performance reason to declare method parameters final in Java?
Why would one mark local variables and method parameters as “final” in Java?
I am using PMD to see the code violations.
Inside a webService Method, I have this below code
public ServiceRequest getData()
{
Status status = new Status();
// code
}
What PMD is suggesting me is that, this local variable status could be declared as final.
My question is, making it final would result in any performance improvements or if not what benefits the code could get?
Taken from the following article: http://www.javapractices.com/topic/TopicAction.do?Id=23
clearly communicates your intent
allows the compiler and virtual machine to perform minor optimizations
clearly flags items which are simpler in behaviour - final says, "If you are looking for complexity, you won't find it here."
This is also discussed in this question: Can excessive use of final hurt more than do good?
final indicates the local variable won't be changed. My feeling is that methods should be so short you should be able to easily understand them and so making the variable final may be a bit redundant.
I prefer to make fields final because making the whole class so short, is a serious limitation. Also fields can have thread safety issues which local variables do not.
I dont know about performance-benefits by making status final, but PMD is suggesting you this, because probably you are never writing on status after its first initialization.
So what you gain by making it final is just that your code is less error-prone - if you declare it final, you cant overwrite it by mistake...
I have read that making something final and then using it in a loop will bring better performance, but is it good for everything? I have lots of places where there isnt a loop but I add final to the local variables. Does it make it slower or is it still good?
Also there are some places where I have a global variable final (e.g. android paint), does it mean I don't have to make it a local final when using it in loops?
The first thing you should consider is; What is the simplest and clearest way I can write this code. Often this performs well.
final local variables is unlikely to affect performance much. They can help clarity when you have long methods, but I would suggest breaking up method is a better approach.
final fields can affect performance to small degree, but a better reason to make it final is to make it clear that this field never changes (which also helps the JIT)
Don't think about performance. final on object member (fields) have significant memory semantics that may improve performance (but more importantly, its often necessary to make the code correctly work at all). You should always put final on object members whenever you can. For local variables however, you should only use it if it will improve code readerability, or can prevent bugs when a maintainer touches your code.
The general consensus of the Java community is that final on every local variables will make the code difficult to read. On the performance front, you can expect no optimization as local variables are easy to analyze for the compiler. In other words, the compiler can figure it out by itself.
From my experience most variables could be declared final.
However, it looks very ugly. That is my main point against it.
And if the part of the program is not performance critical, beware of premature optimization.
It's considered good form to use final where possible (for fields and variables, not classes and methods), if for no other reason than it makes testing easier. Final will never have a negative impact on performance.
Here are my 2 cents:
Use final on attributes to minimize mutability and for documentation purposes, only use final on local variables if they are used in inner/anonymous classes.
DON'T use it for microoptimizations! Especially don't use them on classes or methods because you think it will improve performance. Make classes and methods final to prohibit inheritance or overriding methods.
Final on attributes should not have any impact on performance. Except: in a multi threaded environment where several threads access the same field and "don't know" if they have to relaod it. Final on local variables has no impact at all, as nothing except the local scope can access them anyway.
Final on methods can have an impact during JIT compiling. If a method is final and small the compiler can inline it in loops, as it is clear that no one will have overwritten it.
I usually don't use final on attributes at all, as final attributes can not be loaded from DBs easily etc. Declaring pararameters to methods final lokos ugly (I never assign to them inside my code anyway) but might prevent simple bugs comming from typoes. However if you start using proper names for your variables you unliek make such typoes.
Theoretically, if you make a local variable final it can be optimized. I don't think making them final yourself really improves performance though, because the optimizer probably already detects when your locals don't change. That said, it can't hurt to help it a bit.
In some situations, it would help to change one variable into two, e.g. from this
String a = "foo";
if (lol) a += "bar";
for(.. 1000 ...) doSomething(a);
to
final String a;
{
String ma = "foo";
if (lol) ma += "bar";
a = ma;
}
for(.. 1000 ...) doSomething(a);
Disclaimer: I'm not a JIT expert.
Final variables are constants, therefore the compiler could generate constant value instead of variable referencing instruction. Of course that would improve speed (and commonly size as well).
Also there are some places where I have a global variable final (e.g. android paint), does it mean I don't have to make it a local final when using it in loops?
Sorry, do you mean you don't have to:
final int somefinalvalue = 0;
void amethod() {
final int somefinalvalue = 0; // repeated from global one
}
or what? remember that if you declare local variable which has the same name as global one, that would 'shadow' the global one. i.e. it's actually a totally different variable. if you already have the global one, just use that. no need to re-declare.
I don't think this should be your first concern, as mentioned by #perter-lawrey. First, compiler optimization can very much do the trick; second, there are some tools that can analyze your generated class files and do the same thing, for example, ProGuard: java shrinker, optimizer, obfuscator, and preverifier.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
In Java, you can qualify local variables and method parameters with the final keyword.
public static void foo(final int x) {
final String qwerty = "bar";
}
Doing so results in not being able to reassign x and qwerty in the body of the method.
This practice nudges your code in the direction of immutability which is generally considered a plus. But, it also tends to clutter up code with "final" showing up everywhere. What is your opinion of the final keyword for local variables and method parameters in Java?
You should try to do this, whenever it is appropriate. Besides serving to warn you when you "accidentally" try to modify a value, it provides information to the compiler that can lead to better optimization of the class file. This is one of the points in the book, "Hardcore Java" by Robert Simmons, Jr. In fact, the book spends all of its second chapter on the use of final to promote optimizations and prevent logic errors. Static analysis tools such as PMD and the built-in SA of Eclipse flag these sorts of cases for this reason.
My personal opinion is that it is a waste of time. I believe that the visual clutter and added verbosity is not worth it.
I have never been in a situation where I have reassigned (remember, this does not make objects immutable, all it means is that you can't reassign another reference to a variable) a variable in error.
But, of course, it's all personal preference ;-)
Making a parameter final guarantees that the value used at any location in the method refers to the value passed. Otherwise you have to parse mentally all the code above a given location to know what value the parameter has at that point.
Hence, not using final makes your code less readable, and maintainable, all by itself :)
Final local variables depend on intent, and is less important in my point of view. Depends on what goes on.
In the case of local variables, I tend to avoid this. It causes visual clutter, and is generally unnecessary - a function should be short enough or focus on a single impact to let you quickly see that you are modify something that shouldn't be.
In the case of magic numbers, I would put them as a constant private field anyway rather than in the code.
I only use final in situations where it is necessary (e.g., passing values to anonymous classes).
Because of the (occasionally) confusing nature of Java's "pass by reference" behavior I definitely agree with finalizing parameter var's.
Finalizing local var's seems somewhat overkill IMO.
Yes do it.
It's about readability. It's easier to reason about the possible states of the program when you know that variables are assigned once and only once.
A decent alternative is to turn on the IDE warning when a parameter is assigned, or when a variable (other than a loop variable) is assigned more than once.
final has three good reasons:
instance variables set by constructor only become immutable
methods not to be overridden become final, use this with real reasons, not by default
local variables or parameters to be used in anonimous classes inside a method need to be final
Like methods, local variables and parameters need not to be declared final. As others said before, this clutters the code becoming less readable with very little efford for compiler performace optimisation, this is no real reason for most code fragments.
Although it creates a little clutter, it is worth putting final. Ides e.g eclipse can automatically put the final if you configure it to do so.
Making local variables and method parameters final is essential if you want to pass those parameters into anonymous classes - like you instantiate an anonymous Thread and want to access those params in the body of the run() method.
Apart from that I am not sure of the performance benefits w.r.t better performance through compiler optimization. It is up to the specific compiler implementation whether it wants to optimize it at all...
It will be good to know of any performance stats from using final ...
Why would you want to? You wrote the method, so anyone modifying it could always remove the final keyword from qwerty and reassign it. As for the method signature, same reasoning, although I'm not sure what it would do to subclasses of your class... they may inherit the final parameter and even if they override the method, be unable to de-finalize x. Try it and find out if it would work.
The only real benefit, then, is if you make the parameter immutable and it carries over to the children. Otherwise, you're just cluttering your code for no particularly good reason. If it won't force anyone to follow your rules, you're better off just leaving a good comment as you why you shouldn't change that parameter or variable instead of giving if the final modifier.
Edit
In response to a comment, I will add that if you are seeing performance issues, making your local variables and parameters final can allow the compiler to optimize your code better. However, from the perspective of immutability of your code, I stand by my original statement.
I let Eclipse do it for me when they are being used in an anonymous class, which is increasing due to my use of Google Collection API.
We do it here for the local variables if we think they will not be reassigned or should not be reassigned.
The parameters are not final since we have a Checkstyle-Check which checks for reassigning parameters. Of course nobody would ever want to reassign a parameter variable.