Kevin McMurtrie wrote:
>> In addition to other things mentioned, it's sometimes critical for code
>> maintenance. Objects used as lookup keys must be immutable or the
>> structure that they're in will be damaged. It's best to enforce that
>> during compilation rather than be careful and hope for the best.
Arne Vajhøj wrote:
> That is not a good case for final.
On the contrary, it's an excellent use case for 'final'.
> Final does not protect the object only the ref.
And the object in turn is protected by its own use of 'final'. Finality is
spread from core to surface layer by layer by use of 'final' at each layer.
It's disingenuous to say that 'final' is not useful simply because its scope
is intentionally limited. 'final' *does* protect the object as well as the
reference if it's used properly, i.e., at every layer. *Incorrect* use of
'final' will protect only the reference but not the object.
> And to make the object immutable then don't provide any
> setters.
Spoken in complete disregard for the maintenance portion of the class's
lifecycle. 'final' protects for the future as well as the present.
That doesn't make the object immutable anyway, since internal methods can
mutate the state without 'final' protection. 'final' is a compiler-enforced
prohibition against changes in an object's state even by the object itself.
Furthermore, compile-time constants, for which 'final' is required, have
special semantics, so at least there there is a value.
> With no setters the final is not needed and having both setters
> and final fields will not compile.
Which is evidence of the usefulness of 'final'. You provide evidence for its
value and claim it as proof that you don't need 'final'. Strange.
The point of 'final' is that it raises a compiler error when you combine it
with a setter, whereas your supposedly "immutable" class will silently allow a
future developer to add a setter and destroy your immutability, which as
stated above didn't exist anyway. 'final' lets you catch that contradiction
at compile time, a clear advantage.
You have to consider that a successful class will spend the largest part of
its life in maintenance, not development. 'final' is a tool that lets you
control and simplify maintenance, and prevent future errors. Way too many
coders (I will not dignify them with the sobriquet "developers") code without
regard for the largest part of their artifact's life or for the future
programmers on whom they inflict their carelessness and unprofessionalism.
--
Lew
|