#67 Compile errors from final field suggestions

1.9.0
wont-fix
nobody
5
2015-01-28
2012-03-14
mjomble
No

Happens if the field is assigned conditionally or more than once.

Code to reproduce:

class Example1 {

int something;

Example1() {
if (false) {
something = 1;
}
}

}

class Example2 {

int something;

Example2() {
something = 1;
something = 2;
}

}

UCDetector 1.9.0 suggests using "final" for the field, but adding the keyword introduces a compile error.

Discussion

  • Joerg Spieler
    Joerg Spieler
    2012-03-14

    Your example causes a compile error, but the fields are final, because you only change them in constructor.
    And if you change a field only in constructor, it is a final field.

    If you like the advantage of final fields, I suggest a little refactoring, which causes the compile error to dissapear:

    // The example looks a kind of stupid (if false), but it shows exactly, what I mean
    public class Example1 {

    final int something;

    Bug3504550() {
    if (false) {
    something = 1;
    }
    else {
    something = 2;
    }
    }
    }

    class Example2 {

    final int something;

    Example2() {
    something = getSomething();
    }

    private static int getSomething() {
    int result;
    result = 1;
    result = 2;
    return result;
    }
    }

    If this example does not convince you, switch of the final suggestions.

     
  • mjomble
    mjomble
    2012-03-15

    Yeah, it's pretty easy to refactor, just something I stumbled upon.

    Figured you might want to fix this since it could be considered a bug in UCD that it suggests something that can cause compile errors. Some suggestions, like visibility changes, contain warnings about possible compile errors, but this one didn't.

    So I guess you could also just modify the message :)

     


Anonymous


Cancel   Add attachments