Timo Nentwig said:
Hi!
Most people use final very rarely (so does Sun). Does it make sense to
use final whenever possible?
Let's see:
1. final class.
2. final field.
3. final instance method.
4. final local variable.
5. final method parameter.
1: final class: This is rare. Usually required when
there is some kind of security spoofing possible for
a non-final class. Example: java.lang.String is final
so that a subclass of String can never exist and thus
never spoof or spy on passwords and such. Some classes
have no meaningful inheritance notion, like utility
classes that only have static methods. See "final
instance method" below for more details.
2: final field: Must be assigned by an initializer
expression, an initializer block, or (for an instance
field) by a constructor. Quite common to see final
fields, especially protected or private implementation
dependent fields that contain work objects, like lists.
Note: A field can be shadowed by a method local variable.
If the programmer intends to use a local variable by the
same name as a final field, but forgets to declare the
local variable, the compiler will catch any assignment
to the field in the method. In general, don't use local
variables that shadow fields, unless you really know
what you're doing. Same goes for method parameters.
3: final instance method: This is an alternative to
a final class, where particular instance methods can
be "locked in" to an implementation, but still allow
inheritance of the overall class. Before attaching
"final" to the class, determine whether it would be
more flexible to use "final" on a subset of the instance
methods.
4: final local variable: Good for readability to show
that a variable contains an invariant value. Also good
to prove the programmer's intent to assign only once
to the variable. Instantiating an anonymous inner class
that refers to the local variable (or method parameter)
requires the local variable to be declared final and to
be definitely assigned by the time that class is
instantiated.
5: final method parameter: I generally make all method
parameters final, since they are copy-by-value. Assigning
a new value to a parameter doesn't change anything in
the caller's context. If, for some reason, the algorithm
is better (or more simply) expressed by "massaging" the
value of a parameter, then I would declare a local variable
of the same type and assign the parameter to that local
variable, then use the local variable in the algorithm. This
also helps during debugging to know what was the original
value passed to the method.
Two cents worth. Your mileage may vary.
--
----------------------------
Jeffrey D. Smith
Farsight Systems Corporation
24 BURLINGTON DRIVE
LONGMONT, CO 80501-6906
http://www.farsight-systems.com
z/Debug debugs your Systems/C programs running on IBM z/OS!
Are ISV upgrade fees too high? Check our custom product development!