The quoted text is:
"Relying on such default values, however, is generally considered bad programming style."
Cynically: "it is generally considered that" is often a way of saying that the author hasn't tried to find an authoritative source for the statement being presented.
In this case the assertion is clearly questionable. Evidence: 5 out of 5 Java Style Guides sampled do NOT say anything about whether you should or should relying on default values:
(Note, my methodology for sampling was to look at the first 5 distinct Google search hits for "java style guide". Then I searched each document for "default". This is not a thorough analysis, but it serves to make my point.)
OK. So does it really aid readability of Java code?
This is debatable.
On one hand, a novice Java programmer who hasn't learned about default initialization may be baffled about where the zeros or nulls are coming from. But if they bother to look for an explicit initialization and find there isn't one, that should be sufficient to cause them to read a tutorial or book to find out about default initialization. (You would hope!)
On the other hand, we don't normally expect novice Java programmers to be maintaining production code-bases. For an experienced Java programmer a redundant initialization does not improve readability. It is (at best) noise.
To my mind, the only thing that is achieved by a redundant initialization of a field is to signal to a future reader of your code that you have thought about the the initial value. (As @GhostCat expressed it, default initialization does not communicate intent.)
But conversely if I was that reader, I would not necessarily trust the thinking of the code author. So the value of this "signal" is also questionable.
What about reliability?
In Java it makes no difference. The JLS specifies that default initialization does occur for fields. And conversely, for local variables it is a compilation error to try to use a variable that has not been definitely initialized.
In short, the runtime behavior of a variable that is not explicitly initialized is entirely predictable.
By contrast in languages like C or C++ where variables may not be initialized, the behavior is unspecified, and can lead to crashes, and differences in behavior on different platforms. The case for always explicitly initializing variables is much stronger here.
What about performance?
It should make no difference. The JIT compiler should be able to treat a redundant initialization and default initialization as the same.
private int count = 0;
is code that does nothing, and code that does nothing is clutter. It’s like importing classes from java.lang, or declaring a class withextends Object
. – Influxpublic abstract
method in an interface. – Impedanceprivate
methods in an interface would make no sense, andabstract
is implied. – Circumbendibus