Why isn't "int someVal=0" for an instance field considered dead code?

145 views Asked by At

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

  1. Java automatically initialises instance fields to 0 or equivalent;
  2. 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.

2

There are 2 answers

3
LeffeBrune On

Integer field is a simplistic use case. What if you had something like this, notice the parameterless constructor:

public class DeadCode {

    private List<Integer> someVal = new ArrayList<>();

    public DeadCode() {
    }

    public DeadCode(Iterable<Integer> someVal) {
        this.someVal.addAll(someVal);
    }

    public Iterable<Integer> getSomeVal() {
        return someVal;
    }

    public void addSomeVal(int someVal) {
        this.someVal.add(someVal);
    }
}

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.

8
John Bollinger On

I think the real answer is that many people would find a warning for that code to be pretty annoying.

As a technicality, though, the initializer does not constitute dead code because its effect can, in principle, be observed in an improperly synchronized multithreaded program.