Re: More Flexible "final"
Christian wrote:
Hello
I have been wondering why the final keyword for instance variables is
not more flexible.
Often in my code I find situation when it would have been
helpful/produced nicer code if I were able to change a final variable
while being in the constructor .
Is there any reason behind it that we can't change a final variable
multiple times while we are in the constructor?
The only scenario I can think of where a `semifinal' might
help is when there are multiple constructors, and one of them
chains to another before setting the variable:
private Something instanceVariable;
public SomeClass() {
doLotsOfStuff();
instanceVariable = new Something(42);
}
public SomeClass(int value) {
this();
instanceVariable = new Something(value);
}
The obvious answer in this case is to rearrange responsibilities:
private Something instanceVariable;
public SomeClass() {
this(42);
}
public SomeClass(int value) {
doLotsOfStuff();
instanceVariable = new Something(value);
}
Or perhaps you're worried about running a loop that might
set the variable several times, as in:
private Something instanceVariable();
public SomeClass(Collection<Something> things) {
for (Something thing : things)
if (thing.somePredicate())
instanceVariable = thing;
}
This is easily fixed by introducing a local variable:
private Something instanceVariable;
public SomeClass(Collection<Something> things) {
Something chosen = null;
for (Something thing : things)
if (thing.somePredicate())
chosen = thing;
instanceVariable = chosen;
}
If you have some other situation that seems to cry out for
a `semifinal' variable, please post it.
It would be interesting to know why it is like it is in java.
What benefit does java get by not allowing this?
Simplicity: If the rules are easy to state ("one and only
one assignment") things are easier for both the compiler and
for the human reader. Error detection: Did the programmer truly
intend to make multiple assignments, or did some execution path
escape his notice? Maybe other reasons, too.
Let's turn the question around: What benefit would accrue
from *allowing* `semifinal' variables?
--
Eric Sosman
esosman@ieee-dot-org.invalid