Re: Do we need final parameters?
Jacob wrote:
I see some style gurus recommend using "final" on
parameters that are not modified by the method.
That probably includes more than 99.99% of all parameters,
where the majority of the remaining 0.01% probably are
programming mistakes.
Would it not be better to have this "final" as an implicit
feature defined by the language?
I don't think so. You'd then need a `nonfinal' keyword
to override the implicit finality, or else you'd need to
copy parameters to non-final local variables.
You say you modify only one in ten thousand parameters.
For my part, I find I modify somewhat more than that, usually
when I want to "normalize" them somehow. For example, I have
a Fraction class that represents rational numbers as a pair of
BigInteger values, and in the constructor I want to enforce a
few things:
public Fraction(BigInteger num, BigInteger den) {
// ensure that they're actually BigIntegers
if (num.getClass() != BigInteger.class)
num = new BigInteger(num.getBytes());
if (den.getClass() != BigInteger.class)
den = new BigInteger(den.getBytes());
// ensure that the denominator is non-negative
if (den.signum() < 0) {
den = den.negate();
num = num.negate();
}
// ensure relative primality
if (den.signum() != 0) {
BigInteger gcd = num.gcd(den);
if (! gcd.equals(BigInteger.ONE)) {
num = num.divide(gcd);
den = den.divide(gcd);
}
}
// now in "canonical form;" proceed with construction
...
}
This pattern of "progressive regularization" seems natural to
me: I have three (in this case) conditions to enforce, so I test
each in turn and adjust things as necessary. I *could* leave
the parameters alone and copy them to local variables, but what
benefit would that bring?
[...]
I never use "final" on parameters.
In case you do, why is that so?
I use it when the parameter's value will be referenced
by an inner class:
void method(Thing thing) {
gizmo.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
thing.doSomething(evt);
}
});
}
.... will not compile as it stands. Adding `final' to the
method parameter fixes things.
--
Eric Sosman
esosman@ieee-dot-org.invalid