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

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.

Related

Why shouldn't all function arguments be declared final?

Ok, so I understand why we should declare an argument to be final from this question, but I don't understand why we shouldn't...
Since Java always uses pass by value, this means that we can't return a new value through the given argument, we can only overwrite it, and make the argument useless therefore, because we don't use the passed value...
Is the only benefit of non-final method arguments in Java the fact that you don't have to make a local variable of the arguments' type?
P.S. This question was triggered by PMD's rule of MethodArgumentCouldBeFinal
I can think of only 2 reasons not to make a parameter final:
to save the use of a local variable if you need to overwrite the parameter's value in some edge cases (for instance to put a default if the param is null etc.).
However, I wouldn't consider that a good practice in general.
to save 6 characters per parameter, which improves readability.
Reason 2 is what leads me not to write it most of the time. If you assume that people follow the practice of never assigning a new value to a parameter, you can consider all parameters as implicitly final. Of course, the compiler won't prevent you from assigning a parameter, but I can live with that, given the gain in readability.
It prevents you from making unintentional error in your code. Rule of thumb here is to make each field and each function argument you know you shouldn't change (I mean reference, you still can change value) in your code as final.
So basically its a mean to prevent programmer from shooting their foot. Nothing more.
Whether you've to declare a local variable final or not (method parameter comes under this), is more of the requirement than a convention. You'll not get a certain answer saying you should always use final or you should never use final. Because that is really a personal preference.
I personally mark the parameters or local variables final when I really don't want their values to be changed, and it even shows my intention to other developers not to overwrite the values. But I don't do it for every parameters. Also for some, using final seems to be noise, as that really increases the code base.
Rule of thumb: Don't use it.
Final cannot stop you changing objects, only its reference, and this is because objects in java are, usually, not inmutable.
Take a look to this code:
class Example{
// think about this class as a simple wrapper, a facade or an adapter
SomeClass inner = new SomeClass();
setInnet(Someclass inner){
this.inner = inner;
}
// delegate methods.....
}
Now, in a method:
private void (final Example examp){
....
examp will be always the same object, but inner can vary... And inner is the important object here, the one which makes everything!
This may be an extreme example, and you may think that inner could be final but, if it's a utillery class, maybe it shouldn't. Also it's easy to find a more common example:
public void (final Map map){;
....
//funny things
....
//and then, in a line, someone does:
map.clear()
// no we have the same reference... but the object has change...
....
So, my point against final in arguments is that it's not guaranteed that all the code inside a final class is inmutable and so the final word can end lying you and mascarading a bug...
By putting final in params you can only show wishes, not facts, and for that you should use comments, not code. Moreover: it's a standar (de facto) in java that all arguments are only input arguments (99% of the code). Thus, final word in params is NOISE because it exists and means nothing.
And I don't like noise. So I try to avoid it.
I only use final word to mark the inner variables that will be used in an anonymous inner class (you can avoid marking it if they are effectively final, but it's cleaner and more readable).
UPDATED
final means 'assigned once' which in applied to method arguments means nothing in a program's logic nor in its design.
You can assign the arguments to a new object inside a method and outside there will not be any change.
The only difference putting final in arguments will be that you will not be able to assign that entities to another objects. Assigning arguments is something which may be ugly and something to avoid but its only a style problem and, at that point, the style problem should be the assignation itself and not the ausence of 'final' word.
I think that final is useless in arguments (and so, noise), but if someone is able to find a use of it I'll be happy to learn it. What can I achieve putting 'final' that cannot achieve without putting it?

Why does PMD suggest making fields final?

I created Android application and run static analysis tool PMD on it. And what I don't get is why it is giving me warning and says to declare fields final when possible like in this example.
final City selectedItem = (City) arg0.getItemAtPosition(arg2);
new RequestSender(aaa).execute(xxx, selectedItem.getId());
It just starts inner AsyncTask instance. Is it good style to declare it final and why? For the sake of readability, I created a new object, but PMD says it should be final.
There are two different things here (you are talking both about static and final).
Regarding final, if you create a reference that you will not change (the object itself can be modified), it is a good practice to declare it final, for two reasons :
It helps the compiler to be able to do small performance optimizations
It helps you (or your fellow developer) to understand that this reference will not be changed - it gives a signal.
Regarding static (for a variable, the keyword has different meaning for different kind of structures), it would make your cityItems unique for all objects of its enclosing class. If all objects can use the same value, there is no gain to duplicate it. Again, think not only about the compiler/performance aspect, but also about the signal : if I see a field with "static", I know it is shared among all objects - I do not need additional info or documentation.
In your example, the field should probably be either public static (if it is shared) or private (public or "package protected" fields are breaking encapsulation).

If val is preferred over var in Scala should most object references in Java be marked final?

Because val is similar to final in Java, should most Java object references be marked as final as using val is good practice in Scala?
Certainly it's good practice to make class variables final in Java, encouraging immutability wherever possible.
As for whether local variables -- method parameters, etc. -- should be marked final when not necessary, that's a question of style. Personally, I feel it tends to clutter things when used, unless it's otherwise necessary (e.g. to make a variable accessible in an anonymous inner class).
references should be final as often as possible. It allows for greater runtime optimization, and it helps "contractually" ensure that you (or your code's subsequent maintainer) don't change a reference unexpectedly. To me, it's akin to "private" in the sense that you should make things as private as possible. It offers you future flexibility to refactor without affecting other parts of the codebase (minimizes ripple effect).
As most of this decisions, the usage of final is a discussion for coding conventions.
I myself make all parameters and variables final if they are assigned only once. I think it increases readability of the code.
Eclipse has a SaveAction to add final where ever possible.
Maybe the keyword helps the compiler to detect possible optimization (or maybe future compilers will be able to use this hint)

Private variables/methods in anonymous class?

I have created an anonymous class in which I declare a few variables and methods. My java teacher tells me to make these private. I don't see how changing the modifier makes any difference since these variables and methods are private to the anonymous class anyway, so I prefer to have no modifier at all. Who is right and what makes more sense? See below for example code where I choose no modifier for 'map' and 'convert' rather than making them private.
Collections.sort(list, new Comparator<String>(){
public int compare(String a, String b){
return convert(a).compareTo(convert(b));
}
Map<String, String> map = new HashMap<String, String>();
String convert(String s) {
String u = map.get(s);
if (u == null)
map.put(s, u = s.toUpperCase());
return u;
}
});
I would be tempted to make them private simply for the fact that if you refactor the code and pull the anonymous class out as a standard class (Intellij, for example, can do this at the click of a button), having private fields is what you really want. You won't have to go and rework your classes to match your standard.
Personally I would make them private (and final where possible) anyway - it's just a good habit to be in in general.
To put it another way: if you had to put an access modifier on (if, say, the keyword package was also used as an access modifier) what would you choose? Private, presumably - after all, you don't actually want to grant any other class access, do you?
Now, having decided that private is the most logically appropriate access modifier, I would make that explicit in the code.
Then again, I'd quite possibly not create an anonymous inner class with a member variable anyway - I'd be tempted to turn that into a named nested class instead.
Your professor is right.
Make all class variable private and expose them via properties (if not anonymous).
The general rule of thumb is to keep member data such as variable including your Map object private.
Default modifier is not the same as the private modifier, there're subtle differences.
However, in your case it's more a religious question whether to make convert() default or private. I don't see any advantage in making it private though.
Anyway, your code has a memory leak as the String Cache is never cleared :-P
Also, for even shorter/less code, use the Comparator String.CASE_INSENSITIVE_ORDER:
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
It really doesn't matter, but it's probably a good idea to keep your teacher happy as he/she will be grading you.
I'd say it's a matter of style. You can't access the member map outside out of the anonymous class, but it might be best to define them as private for consistency with other classes.
If this were my code, I would say that if a class is complicated enough to need data members, it might be worth pulling it out into a separate class, in which case I'd certainly make the data members private.
The key point is when you say "I don't see how changing the modifier makes any difference since these variables and methods are private to the anonymous class anyway"... you're assuming a lot about how your class is going to be used. Treat every class like it will be passed around and used in a variety of ways, in other words, use modifiers as appropriate. Besides, it makes the intent of class clear. It's not like Java is a terse language anyway, so you might as well be clear.
I don't see much benefit to marking things private just for the hell of it. It won't really gain you anything and someone reading the code might attach some significance to the choice when there really isn't any.
I would question the need for all this complexity. Take a look at: String.compareToIgnoreCase()
You want these fields to be private, so mark them private.If a member is marked neither public not private then something suspicious is going on. Also mark fields that shouldn't change final. Keeping things standardised means less thinking, or at least less thinking on the irrelevant, and less to change when modifying code.
From a language point of view, the only real difference is that if you have extended a base class in the same package, you have now hidden fields or overridden "package-private" (default access) methods. The members can also be accessed via reflection (without setAccessible) by code in the same package (this can have mobile-code security implications).
difference between default and protected.
protected:
object/method is accessible to all classes that are in the same package, and also accessible to sub/extension classes.
default:
object/method is accessible to all classes that are in the same package.
What is your intention of your object/method and code modifier accordingly.
Do not allow yourself to be confused when you come back to the code after six months because in huge projects you want to know that that object/method is or is not accessed anywhere else.
In three weeks, not just months, you would forget what the intended accessibility of those objects, 101% guaranteed. Then if you had a huge project and you had a hundred modifiers that were not specific and you desperately wanted to update the code, you would be frustrated by the compulsion to run reference check on those 100 objects/methods. May be someone took your jar and found the hidden cookies in them and used them, then you changed your code and broke someone's code.
Code your modifiers according to your intention unless you are either one or more of these:
you have no further desire to work
in large java projects.
you are a
extremely intelligent high
functioning autistic person who has
an indexed memory of every event of
your life and can write a completely functional peer-peer file sharing service
within two weeks on a lap top in a
coffee shop.
you deliberately use it
as another tool to obfuscate your
code.

Best Practice: Java static non final variables

In Java, when should static non final variables be used?
For example
private static int MY_VAR = 0;
Obviously we are not talking about constants here.
public static final int MY_CONSTANT = 1;
In my experience I have often justified them when using a singleton, but then I end up needing to have more than one instance and cause myself great headache and re-factoring.
It seems it is rare that they should be used in practice. What do you think?
Statistics-gathering might use non-final variables, e.g. to count the number of instances created. On the other hand, for that sort of situation you probably want to use AtomicLong etc anyway, at which point it can be final. Alternatively if you're collecting more than one stat, you could end up with a Statistics class and a final reference to an instance of it.
It's certainly pretty rare to have (justifiably) non-final static variables.
When used as a cache, logging, statistics or a debug switch are the obvious reasonable uses. All private, of course.
If you have mutable object assigned to a final field, that is morally the same as having a mutable field.
Some languages, such as Fan, completely disallow mutable statics (or equivalent).
In my experience static non-final variables should only be used for singleton instances. Everything else can be either more cleanly contained by a singleton (such as a cache), or made final (such as a logger reference). However I don't believe in hard and fast rules, so I would take my advice with a grain of salt. That said I would suggest carefully examining any case where you consider declaring a non-final static variable aside from a singleton instance and see if it can be refactored or implemented differently -- i.e. moved into a singleton container or use a final reference to a mutable object.
Static variables can be used to control application-level behaviour, for example specifying global logging level, server to connect with.
I've met such use cases in old appliations, usually coming from other companies.
Nowadays using static variables for such purposes is obviously bad practice, but it wasn't so obvious in, say, 1999. No Spring, no log4j, no Clean code from R.C.Martin etc.
Java language is quite old now, and even if some feature is strongly discouraged now, it was often used in the beginnings. And because of backward compatibility it's unlikely to change.
I think wrapping your statics and providing access via singletons (or at a minimum via static methods) is generally a good idea, since you can better control access and avoid some race condition and synchronization issues.
A static variable means that it is available to the class as a whole so both examples are available to the class as a whole. Final means that the value cannot be changed. So I guess the question is when do you want to a value to be available to an entire class and it cannot be changed after it has been instantiated. My guess would be a constant available to all instantiations of that class. Otherwise if you need something like a population counter then the non-final variable.
Personally for class non-final variables I use the CamelCase notation. It is clear from code that it is a class variable since you have to reference it as such: FooBar.bDoNotRunTests.
On that note, I prefix class instance variables with the this to distinguish them from local scope variables. ex. this.bDoNotRunTests.

Categories

Resources