|
From: Brian S. <bs...@bs...> - 2002-03-14 03:07:34
|
It's about "final" (for fields and variables). Use it. Use it all the
time. Use it any place that a variable is going to be assigned a value
only once. It's useful documentation, and it also helps prevent many
simple typo-type mistakes. It also (duh) ensures that no future code
(without removing "final") can write to said variable!
Two specific places to introduce final, from the class
IndentRuleQuestion.java (which inspired this message). Here's the
original:
public abstract class IndentRuleQuestion implements IndentRule {
private IndentRule _yesRule;
private IndentRule _noRule;
public IndentRuleQuestion(IndentRule yesRule, IndentRule noRule) {
_yesRule = yesRule;
_noRule = noRule;
}
}
(This is obviously a trimmed version of the file!) There are four good
places to introduce final:
public abstract class IndentRuleQuestion implements IndentRule {
private final IndentRule _yesRule;
private final IndentRule _noRule;
public IndentRuleQuestion(final IndentRule yesRule, final IndentRule noRule) {
_yesRule = yesRule;
_noRule = noRule;
}
}
But isn't that a lot of needless typing, you ask? No! The finality of the
fields ensures two things: that you give the field a value at least once
(so it never defaults to null), and that you give a field a value at most
once. OK, fine, that seems reasonable, but why make the parameters final?
Well, first off, they will not in fact be modified. (I wish, by the way,
that final was the default and instead there was a "mutable" keyword!)
Second, it disallows simple typos like "yesRule = _yesRule". (Yes, I know,
in this particular case, that typo would be prevented by _yesRule being
final. But go with me here.)
Anyhow, this is my short story. Use "final" in as many places as you can
possibly stomache it! I know, it clutters things, but it *is* better.
-brian
PS: Some day, there will be better Java source static analysis tools that
will help programmers reason about their programs. These will do much
better when as many values as possible are documented as final!
|