I've been reading the Java Language Specification, and in Chapter 16 there's
an interesting topic called Definite Assignment.
http://tinyurl.com/3fqk8
I'm wondering about the idea of "Deferred Final Automatic Variables" like
the following:
void unflow(boolean flag) {
final int k;
if (flag) {
k = 3;
System.out.println(k);
}
else {
k = 4;
System.out.println(k);
}
}
Most developers I know avoid the final keyword completely. They also try to
always assign an initial value when they define the variable. So instead of
the above example, I'm used to seeing this:
void unflow(boolean flag) {
int k = -1;
if (flag) {
k = 3;
System.out.println(k);
}
else {
k = 4;
System.out.println(k);
}
}
I like the first example better because it's more clear to me. It's saying
that k can only be assigned once, and at a glance, I know the assignment can
only be 3 or 4, nothing else. Even if the method goes on for many
screen-fulls, this assignment is set in stone, even though there's a
condition involved.
My point is, however, that I rarely see deferred assignment in real
projects. The final keyword like in the first example is almost never used
even though, unlike the other uses of final, it has no negative drawback to
inheritance.
Is the first example a better coding practice? If so, why isn't it done
more?
Anthony
--
Got a blog? Post it:
http://www.martin-studio.com/weblog-index/