Why do I get no dead code warning for the initialisation of someVal
here?
public class DeadCode {
private int someVal = 0;
public DeadCode(int someVal) {
this.someVal = someVal;
}
public int getSomeVal() {
return someVal;
}
public void setSomeVal(int someVal) {
this.someVal = someVal;
}
}
The Java compiler is supposed to pick up on dead code and issue a warning; but this is dead twice over, and passes by without a hitch.
It's dead twice over because
- Java automatically initialises instance fields to
0
or equivalent; - the value of
someVal
can't be read without being written to.
I realise that the compiler can elide the assignment if it wants to, but that's true (by definition) of all dead code.
If there is a distinction to be made between dead code and code that has no effect, then I would expect
The assignment to variable
someVal
has no effect.
which is what I would get if I wrote
someVal = someVal;
in my code. But I don't get that either.
In any case, Wikipedia sees dead code elimination as removal of code that has no effect on program results; and this is certainly a case of that.
Integer field is a simplistic use case. What if you had something like this, notice the parameterless constructor:
You have to create a list, yes you could do it in the constructor Now the compiler needs to be a lot more intelligent to be able to determine in which cases it wasteful to initialize field. I guess they opted for consistent and straightforward behavior.