Re: Usefulness of "final"
markspace <markspace@nospam.nospam> wrote:
Honestly I'm shocked at your response and I think you're missing the
point by a wide margin. Are you trying to tell me that final fields are
not involved in immutability in Java?
For what it's worth, they're not:
public class ThisIsImmutable {
private String cantChangeMe;
public ThisIsImmutable(String value) {
this.cantChangeMe = value;
}
public String getCantChangeMe() {
return this.cantChangeMe;
}
}
public class ThisIsNot {
private final Map<String, Integer> positionMap = new HashMap<>();
public void store(String key) {
this.positionMap.put(key, positionMap.size());
}
public Integer position(String key) {
return this.positionMap.get(key);
}
public void clear() {
this.positionMap.clear();
}
}
Now, it's certainly good practice to use "final" to help mark fields
that should not be reassigned, but "final" is neither sufficient nor
necessary to enforce immutability. (And with reflection mixed in the
bag it's not even sufficient to enforce non-reassignability, but
that's another story.)
As for the use of "final" for parameters and local variables, my
personal opinion is that the semantics of "final" are too weak to make
it worth the bother. As Java methods are pass-by-value, variable
reassignment just isn't a real source for problems so why guard
against it?
--
Leif Roar Moldskred