Are all compile-time constants inlined? - java

Let's say I have a class like this:
class ApplicationDefs{
public static final String configOption1 = "some option";
public static final String configOption2 = "some other option";
public static final String configOption3 = "yet another option";
}
Many of the other classes in my application are using these options. Now, I want to change one of the options alone and deploy just the compiled class.
But if these fields are in-lined in the consumer classes this becomes impossible right?
Is there any option to disable the in-lining of compile time constants?

You can use String.intern() to get the desired effect, but should comment your code, because not many people know about this. i.e.
public static final String configOption1 = "some option".intern();
This will prevent the compile time inline. Since it is referring to the exact same string that the compiler will place in the perm, you aren't creating anything extra.
As an alternative you could always do
public static final String configOption1 = "some option".toString();
which might be easier to read. Either way, since this is a bit odd you should comment the code to inform those maintaining it what you are doing.
Edit:
Found another SO link that gives references to the JLS, for more information on this.
When to use intern() on String literals

No, it's part of the JLS, I'm afraid. This is touched upon, briefly, in Java Puzzlers but I don't have my copy to hand.
I guess you might consider having these constants defined in a properties file, and have the class that loads them periodically.
Reference: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5313

No. You could replace them with a static method call, though, like:
class ApplicationDefs {
public static String configOption1() { return "some option"; }
}
Granted, it’s not beautiful but it would fulfill your requirement. :)

Actually, if you remove the final keyword the constants stop being compile-time constants and then your configuration will work like you want.
However, it is strongly suggested that if this is indeed some sort of configuration you are trying to do, you should move to to a more manageable way than constants in some class file.

You can inhibit inlining by making your constant non-compile time constants...
For instance, null is not a compile time constant. Any expression involving a non-compile time constant is not a compile time constant, although javac may do constant folding within the compilation unit.
public static final String configOption1 = null!=null?"": "some option";

There is nothing here that says these values should be inlined. You are just declaring some public, static members. Those other classes are using the values of these members. No inlining is asked. Even the final keyword
But for performance reasons, some JVMs may inline these values in those other classes. This is an optimization. No optimization should change the behaviour of a program. So if you change the definition of these members, the JVM should un-inline the previous values.
This is why there is no way to turn inlining off. Either the JVM does not inline and there is no problem or if it is inlined, the JVM guarantee the un-inlining.
I am not sure what happens when you import statically this class. I think (not sure) the inlining is performed and may cause the trouble you mention. If that is the case, you could basically delete the static import and you are ok.

Related

when exactly are we supposed to use "public static final String"?

I have seen much code where people write public static final String mystring = ...
and then just use a value.
Why do they have to do that? Why do they have to initialize the value as final prior to using it?
UPDATE
Ok, thanks all for all your answers, I understand the meaning of those key (public static final). What I dont understand is why people use that even if the constant will be used only in one place and only in the same class. why declaring it? why dont we just use the variable?
final indicates that the value of the variable won't change - in other words, a constant whose value can't be modified after it is declared.
Use public final static String when you want to create a String that:
belongs to the class (static: no instance necessary to use it), that
won't change (final), for instance when you want to define a String constant that will be available to all instances of the class, and to other objects using the class, and that
will be a publicly accessible part of the interface that the class shows the world.
Example:
public final static String MY_CONSTANT = "SomeValue";
// ... in some other code, possibly in another object, use the constant:
if (input.equals(MyClass.MY_CONSTANT)
Similarly:
public static final int ERROR_CODE = 127;
It isn't required to use final, but it keeps a constant from being changed inadvertently during program execution, and serves as an indicator that the variable is a constant.
Even if the constant will only be used - read - in the current class and/or in only one place, it's good practice to declare all constants as final: it's clearer, and during the lifetime of the code the constant may end up being used in more than one place.
Furthermore using final may allow the implementation to perform some optimization, e.g. by inlining an actual value where the constant is used.
Finally note that final will only make truly constant values out of primitive types, String which is immutable, or other immutable types. Applying final to an object (for instance a HashMap) will make the reference immutable, but not the state of the object: for instance data members of the object can be changed, array elements can be changed, and collections can be manipulated and changed.
Static means..You can use it without instantiate of the class or using any object.
final..It is a keyword which is used for make the string constant. You can not change the value of that string. Look at the example below:
public class StringTest {
static final String str = "Hello";
public static void main(String args[]) {
// str = "world"; // gives error
System.out.println(str); // called without the help of an object
System.out.println(StringTest.str);// called with class name
}
}
Thanks
The keyword final means that the value is constant(it cannot be changed). It is analogous to const in C.
And you can treat static as a global variable which has scope. It basically means if you change it for one object it will be changed for all just like a global variable(limited by scope).
Hope it helps.
static means that the object will only be created once, and does not have an instance object containing it. The way you have written is best used when you have something that is common for all objects of the class and will never change. It even could be used without creating an object at all.
Usually it's best to use final when you expect it to be final so that the compiler will enforce that rule and you know for sure. static ensures that you don't waste memory creating many of the same thing if it will be the same value for all objects.
final indicates that the value cannot be changed once set. static allows you to set the value, and that value will be the same for ALL instances of the class which utilize it. Also, you may access the value of a public static string w/o having an instance of a class.
 public makes it accessible across the other classes. You can use it without instantiate of the class or using any object.
 static makes it uniform value across all the class instances.
It ensures that you don't waste memory creating many of the same thing if it will be the same value for all the objects.
 final makes it non-modifiable value. It's a "constant" value which is same across all the class instances and cannot be modified.
You do not have to use final, but the final is making clear to everyone else - including the compiler - that this is a constant, and that's the good practice in it.
Why people doe that even if the constant will be used only in one place and only in the same class: Because in many cases it still makes sense. If you for example know it will be final during program run, but you intend to change the value later and recompile (easier to find), and also might use it more often later-on. It is also informing other programmers about the core values in the program flow at a prominent and combined place.
An aspect the other answers are missing out unfortunately, is that using the combination of public final needs to be done very carefully, especially if other classes or packages will use your class (which can be assumed because it is public).
Here's why:
Because it is declared as final, the compiler will inline this field during compile time into any compilation unit reading this field. So far, so good.
What people tend to forget is, because the field is also declared public, the compiler will also inline this value into any other compile unit. That means other classes using this field.
What are the consequences?
Imagine you have this:
class Foo {
public static final String VERSION = "1.0";
}
class Bar {
public static void main(String[] args) {
System.out.println("I am using version " + Foo.VERSION);
}
}
After compiling and running Bar, you'll get:
I am using version 1.0
Now, you improve Foo and change the version to "1.1".
After recompiling Foo, you run Bar and get this wrong output:
I am using version 1.0
This happens, because VERSION is declared final, so the actual value of it was already in-lined in Bar during the first compile run. As a consequence, to let the example of a public static final ... field propagate properly after actually changing what was declared final (you lied!;), you'd need to recompile every class using it.
I've seen this a couple of times and it is really hard to debug.
If by final you mean a constant that might change in later versions of your program, a better solution would be this:
class Foo {
private static String version = "1.0";
public static final String getVersion() {
return version;
}
}
The performance penalty of this is negligible, since JIT code generator will inline it at run-time.
Usually for defining constants, that you reuse at many places making it single point for change, used within single class or shared across packages. Making a variable final avoid accidental changes.
Why do people use constants in classes instead of a variable?
readability and maintainability,
having some number like 40.023 in your code doesn't say much about what the number represents, so we replace it by a word in capitals like "USER_AGE_YEARS". Later when we look at the code its clear what that number represents.
Why do we not just use a variable? Well we would if we knew the number would change, but if its some number that wont change, like 3.14159.. we make it final.
But what if its not a number like a String? In that case its mostly for maintainability, if you are using a String multiple times in your code, (and it wont be changing at runtime) it is convenient to have it as a final string at the top of the class. That way when you want to change it, there is only one place to change it rather than many.
For example if you have an error message that get printed many times in your code, having final String ERROR_MESSAGE = "Something went bad." is easier to maintain, if you want to change it from "Something went bad." to "It's too late jim he's already dead", you would only need to change that one line, rather than all the places you would use that comment.
public makes it accessible across other classes.
static makes it uniform value across all the class instances.
final makes it non-modifiable value.
So basically it's a "constant" value which is same across all the class instances and which cannot be modified.
With respect to your concern "What I don't understand is why people use that even if the constant will be used only in one place and only in the same class. Why declaring it? Why don't we just use the variable?"
I would say since it is a public field the constant value can also be used elsewhere in some other class using ClassName.value. eg: a class named Math may have PI as final static long value which can be accessed as Math.PI.
It is kind of standard/best practice.
There are already answers listing scenarios, but for your second question:
Why do they have to do that? Why do they have to initialize the value as final prior to using it?
Public constants and fields initialized at declaration should be "static final" rather than merely "final"
These are some of the reasons why it should be like this:
Making a public constant just final as opposed to static final leads to duplicating its value for every instance of the class, uselessly increasing the amount of memory required to execute the application.
Further, when a non-public, final field isn't also static, it implies that different instances can have different values. However, initializing a non-static final field in its declaration forces every instance to have the same value owing to the behavior of the final field.
This is related to the semantics of the code. By naming the value assigning it to a variable that has a meaningful name (even if it is used only at one place) you give it a meaning. When somebody is reading the code that person will know what that value means.
In general is not a good practice to use constant values across the code. Imagine a code full of string, integer, etc. values. After a time nobody will know what those constants are. Also a typo in a value can be a problem when the value is used on more than one place.
I think these are all clear explanations. But, Let me clarify it by giving a java inbuild example.
In java, most would have used System.out.println()
The system is a class and out is a PrintStream class.
So what java says is I will take care of the initialization of the out object(PrintStream) and keep the initialization private to myself in the System class.
public final class System {
public final static PrintStream out = null;
//Some initialization done by system class which cannot be changed as it is final.
}
You just access the println method statically without worrying about its initialization.

Speed optimizing: private and public variables - Java

I am asking this question purely for the speed aspects of the question.
What is the difference in speed between getting the value from an object when it is private or public (Java)?
class MyClass {
public int myInt = 5;
}
class MyOtherClass {
private int myInt = 5;
public int getMyInt() {
return myInt;
}
}
class MyMainClass {
public static void main (String [] args) {
MyClass myObject = new MyClass();
MyOtherClass myOtherObject = new MyOtherClass();
// which is faster?
System.out.println(myObject.myInt);
System.out.println(myOtherObject.getMyInt ());
}
}
I know I can test it, but if anyone alreay knows it, it can't hurt :)
Thanks in advance!
Public and private access is nothing more than determining at compile time whether or not you have access to a variable. At run time, they are exactly the same. This means if you can trick the JVM into thinking you have access (through reflection, unsafe, or modifying the bytecode) then you can. Public and private is just compile time information. That's not to say it doesn't get stored in the bytecode, because it does, but only so it can be referenced if something tries to compile against it.
The access modifier on the field doesn't make any difference in speed, but invoking the accessor method does.
However, the difference isn't great, and is likely to diminish after repeated invocations due to JIT compiler optimizations. It depends on your situation, but I haven't found a case where performance concerns justified the elimination of an accessor. Let good design principles drive your decisions.
One good design principle that will help performance in this case is to prohibit inheritance unless you know it is needed and have taken steps to support it. In particular, declaring the class to be final (or at least the accessor method) will provide faster method dispatch and might also serve as a hint to the JITC to inline more agressively.
Keeping accessors final also allows the compiler to inline calls to the accessor. If the field is private, calls to the accessor from within the class can be inlined (and in a good design, these are far and away the most common case), while a package accessible field can be inlined throughout the package, etc.
As far as I know, when you're calling a getter or any function that will just return some value and nothing else, this method will get inlined so there's no difference whatsoever between the method call and the dirrect access of the field.
You ask about accessing private vs. public variables, but your code example and comment to glowcoder hint that you're really asking about private fields vs. public methods (or, fields vs. methods ... as glowcoder correctly said, public vs. private has no impact on performance).
Many modern compilers will optimize calls to short methods to be equivalent to access to the field they wrap (by inlining the call), but it's entirely possible that a given Java environment will perform a function call instead (which is slightly slower) to invoke the method.
It's up to the particular compiler whether to generate inline code or a function call. Lacking knowledge of which java compiler you're using (and possibly which compiler options), it's not possible to say for sure.
From a performance perspective, the difference is infinitesimal, if there's any difference at all. The compiler is going to optimize this code almost identically, and once the code is compiled, the JVM is going to treat public and private variables exactly the same way (I don't believe it even knows about the distinction between public and private post-compilation).
From a pragmatic standpoint, it's difficult to conceive of any possible scenario where it's worth breaking the traditional Java attribute access pattern for performance purposes. There was a similar question asked on StackOverflow on this subject for C++, and the answers are just as relevant for Java:
Any performance reason to put attributes protected/private?

Do javac or Hotspot automatically add 'final' as an optimisation of invariant variables?

The consensus seems to be that there is a performance benefit to marking member variables as final because they never need reloading from main memory. My question is, do javac or Hotspot automatically do this for me when it's obvious the variable cannot change. eg will javac make 'x' final in this class below...
public class MyClass {
private String x;
MyClass(String x) {
this.x = x;
}
public String getX() {
return x;
}
}
On a secondary point, has anyone produced empirical evidence that marking members as final makes code run faster? Any benefit is surely negligible in any application making remote calls or database lookups?
Like many performance "enhancements" it is usually a better to ask; What is easier to understand and reason about? e.g. if a field is final I know it won't be changed anywhere. This is often leads to more optimial code, but more importantly it should be more maintainable code. ;)
Certainly, I make any field which can be final as final. Personally I would have preferred that final be the default behaviour and you had to use a keyword like var to make it mutable.
Allowing javac to do this would be a blunder. As there might be code in a different jar which may rely on the code being compiled (modularity), changing code at compile time for optimization sake is not a feasible option.
As for the second argument "never need reloading from the main memory", one needs to remember that most instance variables are cached. final only indicates immutability, it does not guarantee volatility (volatile == always get latest from main memory). Hence the need for locks and volatile keyword in multi-threaded environment.
As for the case with hotspot, I have no clue, and would like to hear more about it. final constants may be in-lined at compile time, thus allowing moderate performance gains. Reference to a question on in-lining in java
Edit: Note that final indicates immutability needs to be taken with a grain of salt. It does not guarantee that the state cannot change, it only specifies that the object reference can be modified. final indicates immutability for primitive data types
AFAIK, they do not, and thus, you suffer minor penalty. This, however, can be done automatically with IDE tools like Eclipse "Cleanup" feauture.
I believe a modern JVM (the Hotspot compiler) does detect that the value doesn't change, so there is no performance benefit in making parameters or variables final yourself. (If this is wrong, please provide a link or test case.) There is one exception: constants (static final).
However, this may be different with final methods and classes. It may improve performance in this case (I'm not completely sure in what cases). By the way, what does improve performance a little bit is making functions static (if possible).
The problem I have with final is that it clutters the code. It would be nice if final would be the default.

Are there inline functions in java?

Is there a concept of inline functions in java, or its replaced something else? If there is, how is it used? I've heard that public, static and final methods are the inline functions. Can we create our own inline function?
In Java, the optimizations are usually done at the JVM level. At runtime, the JVM perform some "complicated" analysis to determine which methods to inline. It can be aggressive in inlining, and the Hotspot JVM actually can inline non-final methods.
The java compilers almost never inline any method call (the JVM does all of that at runtime). They do inline compile time constants (e.g. final static primitive values). But not methods.
For more resources:
Article: The Java HotSpot Performance Engine: Method Inlining Example
Wiki: Inlining in OpenJDK, not fully populated but contains links to useful discussions.
No, there is no inline function in java. Yes, you can use a public static method anywhere in the code when placed in a public class. The java compiler may do inline expansion on a static or final method, but that is not guaranteed.
Typically such code optimizations are done by the compiler in combination with the JVM/JIT/HotSpot for code segments used very often. Also other optimization concepts like register declaration of parameters are not known in java.
Optimizations cannot be forced by declaration in java, but done by compiler and JIT. In many other languages these declarations are often only compiler hints (you can declare more register parameters than the processor has, the rest is ignored).
Declaring java methods static, final or private are also hints for the compiler. You should use it, but no garantees. Java performance is dynamic, not static. First call to a system is always slow because of class loading. Next calls are faster, but depending on memory and runtime the most common calls are optimized withinthe running system, so a server may become faster during runtime!
Java does not provide a way to manually suggest that a method should be inlined. As #notnoop says in the comments, the inlining is typically done by the JVM at execution time.
What you said above is correct. Sometimes final methods are created as inline, but there is no other way to explicitly create an inline function in java.
Well, there are methods could be called "inline" methods in java, but depending on the jvm. After compiling, if the method's machine code is less than 35 byte, it will be transferred to a inline method right away, if the method's machine code is less than 325 byte, it could be transferred into a inline method, depending on the jvm.
Real life example:
public class Control {
public static final long EXPIRED_ON = 1386082988202l;
public static final boolean isExpired() {
return (System.currentTimeMillis() > EXPIRED_ON);
}
}
Then in other classes, I can exit if the code has expired. If I reference the EXPIRED_ON variable from another class, the constant is inline to the byte code, making it very hard to track down all places in the code that checks the expiry date. However, if the other classes invoke the isExpired() method, the actual method is called, meaning a hacker could replace the isExpired method with another which always returns false.
I agree it would be very nice to force a compiler to inline the static final method to all classes which reference it. In that case, you need not even include the Control class, as it would not be needed at runtime.
From my research, this cannot be done. Perhaps some Obfuscator tools can do this, or, you could modify your build process to edit sources before compile.
As for proving if the method from the control class is placed inline to another class during compile, try running the other class without the Control class in the classpath.
so, it seems there arent, but you can use this workaround using guava or an equivalent Function class implementation, because that class is extremely simple, ex.:
assert false : new com.google.common.base.Function<Void,String>(){
#Override public String apply(Void input) {
//your complex code go here
return "weird message";
}}.apply(null);
yes, this is dead code just to exemplify how to create a complex code block (within {}) to do something so specific that shouldnt bother us on creating any method for it, AKA inline!
Java9 has an "Ahead of time" compiler that does several optimizations at compile-time, rather than runtime, which can be seen as inlining.

Using the "final" modifier whenever applicable in Java [closed]

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 10 years ago.
In Java, there is a practice of declaring every variable (local or class), parameter final if they really are.
Though this makes the code a lot more verbose, this helps in easy reading/grasping of the code and also prevents mistakes as the intention is clearly marked.
What are your thoughts on this and what do you follow?
I think it all has to do with good coding style. Of course you can write good, robust programs without using a lot of final modifiers anywhere, but when you think about it...
Adding final to all things which should not change simply narrows down the possibilities that you (or the next programmer, working on your code) will misinterpret or misuse the thought process which resulted in your code. At least it should ring some bells when they now want to change your previously immutable thing.
At first, it kind of looks awkward to see a lot of final keywords in your code, but pretty soon you'll stop noticing the word itself and will simply think, that-thing-will-never-change-from-this-point-on (you can take it from me ;-)
I think it's good practice. I am not using it all the time, but when I can and it makes sense to label something final I'll do it.
Obsess over:
Final fields - Marking fields as final forces them to be set by end of construction, making that field reference immutable. This allows safe publication of fields and can avoid the need for synchronization on later reads. (Note that for an object reference, only the field reference is immutable - things that object reference refers to can still change and that affects the immutability.)
Final static fields - Although I use enums now for many of the cases where I used to use static final fields.
Consider but use judiciously:
Final classes - Framework/API design is the only case where I consider it.
Final methods - Basically same as final classes. If you're using template method patterns like crazy and marking stuff final, you're probably relying too much on inheritance and not enough on delegation.
Ignore unless feeling anal:
Method parameters and local variables - I RARELY do this largely because I'm lazy and I find it clutters the code. I will fully admit that marking parameters and local variables that I'm not going to modify is "righter". I wish it was the default. But it isn't and I find the code more difficult to understand with finals all over. If I'm in someone else's code, I'm not going to pull them out but if I'm writing new code I won't put them in. One exception is the case where you have to mark something final so you can access it from within an anonymous inner class.
You really need to understand the full use of the final keyword before using it. It can apply to and has differing affects on variables, fields, methods and classes
I’d recommend checking out the article linked to below for more details.
Final Word On the final Keyword
The final modifier, especially for variables, is a means to have the compiler enforce a convention that is generally sensible: make sure a (local or instance) variable is assigned exactly once (no more no less). By making sure a variable is definitely assigned before it is used, you can avoid common cases of a NullPointerException:
final FileInputStream in;
if(test)
in = new FileInputStream("foo.txt");
else
System.out.println("test failed");
in.read(); // Compiler error because variable 'in' might be unassigned
By preventing a variable from being assigned more than once, you discourage overbroad scoping. Instead of this:
String msg = null;
for(int i = 0; i < 10; i++) {
msg = "We are at position " + i;
System.out.println(msg);
}
msg = null;
You are encouraged to use this:
for(int i = 0; i < 10; i++) {
final String msg = "We are at position " + i;
System.out.println(msg);
}
Some links:
The final story (free chapter of the book "Hardcore Java")
Some final patterns
Definite assignment
I'm pretty dogmatic about declaring every possible variable final. This includes method parameters, local variables, and rarely, value object fields. I've got three main reasons for declaring final variables everywhere:
Declaring Intention: By declaring a final variable, I am stating that this variable is meant to be written to only once. It's a subtle hint to other developers, and a big hint to the compiler.
Enforcing Single-use Variables: I believe in the idea that each variable should have only one purpose in life. By giving each variable only one purpose, you reduce the time it takes to grok the purpose of that particular variable while debugging.
Allows for Optimization: I know that the compiler used to have performance enhancement tricks which relied specifically on the immutability of a variable reference. I like to think some of these old performance tricks (or new ones) will be used by the compiler.
However, I do think that final classes and methods are not nearly as useful as final variable references. The final keyword, when used with these declarations simply provide roadblocks to automated testing and the use of your code in ways that you could have never anticipated.
Effective Java has an item that says "Favour immutable objects". Declaring fields as final helps you take some small steps towards this, but there is of course much more to truly immutable objects than that.
If you know that objects are immutable they can be shared for reading among many threads/clients without synchronization worries, and it is easier to reason about how the program runs.
I have never been in a situation where having a final keyword on a variable has stopped me from making a mistake, so for the moment I think it's a giant waste of time.
Unless there is a real reason for doing it (as in you want to make a specific point about that variable being final) I would rather not do it since I find it makes the code less readable.
If, however, you don't find it makes the code harder to read or longer to write then by all means go for it.
Edit: As a clarification (and an attempt to win back down-votes), I'm not saying don't mark constants as final, I'm saying don't do stuff like:
public String doSomething() {
final String first = someReallyComplicatedExpressionToGetTheString();
final String second = anotherReallyComplicatedExpressionToGetAnother();
return first+second;
}
It just makes code (in my opinion) harder to read.
It's also worth remembering that all final does is prevent you from reassigning a variable, it doesn't make it immutable or anything like that.
Final should always be used for constants. It's even useful for short-lived variables (within a single method) when the rules for defining the variable are complicated.
For example:
final int foo;
if (a)
foo = 1;
else if (b)
foo = 2;
else if (c)
foo = 3;
if (d) // Compile error: forgot the 'else'
foo = 4;
else
foo = -1;
Sounds like one of the biggest argument against using the final keyword is that "it's unnecessary", and it "wastes space".
If we acknowledge the many benefits of "final" as pointed out by many great posts here, while admitting it takes more typing and space, I would argue that Java should have made variables "final" by default, and require that things be marked "mutable" if the coder wants it to be.
I use final all the time for object attributes.
The final keyword has visibility semantics when used on object attributes. Basically, setting the value of a final object attribute happens-before the constructor returns. This means that as long as you don't let the this reference escape the constructor and you use final for all you attributes, your object is (under Java 5 semantics) guarenteed to be properly constructed, and since it is also immutable it can be safely published to other threads.
Immutable objects is not just about thread-safety. They also make it a lot easier to reason about the state transitions in your program, because the space of what can change is deliberately and, if used consistently, thoroughly limited to only the things that should change.
I sometimes also make methods final, but not as often. I seldomly make classes final. I generally do this because I have little need to. I generally don't use inheritance much. I prefer to use interfaces and object composition instead - this also lends itself to a design that I find is often easier to test. When you code to interfaces instead of concrete classes, then you don't need to use inheritance when you test, as it is, with frameworks such as jMock, much easier to create mock-objects with interfaces than it is with concrete classes.
I guess I should make the majority of my classes final, but I just haven't gotten into the habbit yet.
I have to read a lot of code for my job. Missing final on instance variables is one of the top things to annoy me and makes understanding the code unnecessarily difficult. For my money, final on local variables causes more clutter than clarity. The language should have been designed to make that the default, but we have to live with the mistake. Sometimes it is useful particularly with loops and definite assignment with an if-else tree, but mostly it tends to indicate your method is too complicated.
final should obviously be used on constants, and to enforce immutability, but there is another important use on methods.
Effective Java has a whole item on this (Item 15) pointing out the pitfalls of unintended inheritance. Effectively if you didn't design and document your class for inheritance, inheriting from it can give unexpected problems (the item gives a good example). The recommendation therefore is that you use final on any class and/or method that wasn't intended to be inherited from.
That may seem draconian, but it makes sense. If you are writing a class library for use by others then you don't want them inheriting from things that weren't designed for it - you will be locking yourself into a particular implementation of the class for back compatibility. If you are coding in a team there is nothing to stop another member of the team from removing the final if they really have to. But the keyword makes them think about what they are doing, and warns them that the class they are inheriting from wasn't designed for it, so they should be extra careful.
Another caveat is that many people confuse final to mean that the contents of the instance variable cannot change, rather than that the reference cannot change.
Even for local variables, knowing that it is declared final means that I don't need to worry about the reference being changed later on. This means that when debugging and I see that variable later on, I am confident that it is referring to the same object. That is one less thing I need to worry about when looking for a bug.
A bonus is that if 99% of variables are declared final, then the few variables which really are variable stand out better.
Also, the final lets the compiler find some more possible stupid mistakes that might otherwise go unnoticed.
Choosing to type final for each parameter in each method will produce so much irritation both for coders and code readers.
Once irritation goes beyond reasonable switch to Scala where arguments are final by default.
Or, you can always use code styling tools that will do that automatically for you. All IDEs have them implemented or as plugins.
Final when used with variables in Java provides a substitute for constant in C++. So when final and static is used for a variable it becomes immutable. At the same time makes migrated C++ programmers pretty happy ;-)
When used with reference variables it does not allow you to re-reference the object, though the object can be manipulated.
When final is used with a method, it does not allow the method to be over-ridden by the subclasses.
Once the usage is very clear it should be used with care. It mainly depends on the design as using final on the method would not help polymorphism.
One should only use it for variables when you are damn sure that the value of the variable will/should never be changed. Also ensure that you follow the coding convention encouraged by SUN.for eg: final int COLOR_RED = 1; (Upper case seperated by underscore)
With a reference variable, use it only when we need a an immutable reference to a particular object.
Regarding the readability part, ensue that comments play a very important role when using the final modifier.
I never use them on local variables, there is little point for the added verbosity. Even if you don't think the variable should be reassigned, that will make little difference to the next person altering that code that thinks otherwise, and since the code is being changed, any original purpose for making it final may no longer be valid. If it is just for clarity, I believe it fails due to the negative effects of the verbosity.
Pretty much the same applies to member variables as well, as they provide little benefit, except for the case of constants.
It also has no bearing on immutability, as the best indicator of something being immutable is that it is documented as such and/or has no methods that can alter the object (this, along with making the class final is the only way to guarantee that it is immutable).
But hey, that's just my opinion :-)
I set up Eclipse to add final on all fields and attributes which are not modified. This works great using the Eclipse "save actions" which adds these final modifiers (among other things) when saving the file.
Highly recommended.
Check out my blog post of Eclipse Save Actions.
For arguments I'm think they're not needed. Mostley they just hurt readabillity. Rreassigning an argument variable is so insanely stupid that I should be pretty confident that they can be treated as constants anyway.
The fact that Eclipse colors final red makes it easier to spot variable declarations in the code which I think improves readbillity most of the time.
I try to enforce the rule that any and all variables should be final it there isn't an extremley valid reason not to. It's so much easier to answer the "what is this variable?" question if you just have to find the initilization and be confident that that is it.
I actually get rather nervous around non-final variables now a days. It's like the differnce between having a knife hanging in a thread abouve your head, or just having it you kitchen drawer...
A final variable is just a nice way to lable values.
A non-final variable is bound to part of some bug-prone algorithm.
One nice feature is that when the option to use a variable in out of the question for an algorithm most of the time the sollution is to write a method instead, which usually improves the code significantly.
I've been coding for a while now and using final whenever I can. After doing this for a while (for variables, method parameters and class attributes), I can say that 90% (or more) of my variables are actually final. I think the benefit of NOT having variables modified when you don't want to (I saw that before and it's a pain sometimes) pays for the extra typing and the extra "final" keywords in your code.
That being said, if I would design a language, I would make every variable final unless modified by some other keyword.
I don't use final a lot for classes and methods, thought. This is a more or less complicated design choice, unless your class is a utility class (in which case you should have only one private constructor).
I also use Collections.unmodifiable... to create unmodifiable lists when I need to.
Using anonymous local classes for event listeners and such is a common pattern in Java.
The most common use of the final keyword is to make sure that variables in scope are accessible to the even listener.
However, if you find yourself being required to put a lot of final statements in your code. That might be a good hint you're doing something wrong.
The article posted above gives this example:
public void doSomething(int i, int j) {
final int n = i + j; // must be declared final
Comparator comp = new Comparator() {
public int compare(Object left, Object right) {
return n; // return copy of a local variable
}
};
}
I use it for constants inside and outside methods.
I only sometimes use it for methods because I don't know if a subclass would NOT want to override a given method(for whatever reasons).
As far as classes, only for some infrastructure classes, have I used final class.
IntelliJ IDEA warns you if a function parameter is written to inside a function. So, I've stopped using final for function arguments. I don't see them inside java Runtime library as well.
I hardly use final on methods or classes because I like allowing people to override them.
Otherwise, I only use finally if it is a public/private static final type SOME_CONSTANT;
Marking the class final can also make some method bindings happen at compile time instead of runtime.
Consider "v2.foo()" below - the compiler knows that B cannot have a subclass, so foo() cannot be overridden so the implementation to call is known at compile time. If class B is NOT marked final, then it's possible that the actual type of v2 is some class that extends B and overrides foo().
class A {
void foo() {
//do something
}
}
final class B extends A {
void foo() {
}
}
class Test {
public void t(A v1, B v2) {
v1.foo();
v2.foo();
}
}
Using final for constants is strongly encouraged. However, I wouldn't use it for methods or classes (or at least think about it for a while), because it makes testing harder, if not impossible. If you absolutely must make a class or method final, make sure this class implements some interface, so you can have a mock implementing the same interface.

Categories

Resources