#338 a += b is the same as a = a + b... Right? Wrong!

Check (274)

Check this out:


I have not found this check in Checkstyle. Have I
missed it? If not available in Checkstyle, it should be
part of the excellent Checkstyle.



  • Lars Kühne

    Lars Kühne - 2004-12-14

    Logged In: YES

    Such a check would requires type information about a and b.
    This is not possible with the current checkstyle architecture.

    Maybe it can be done by analyzing the byte code, not sure.

  • fengqian

    fengqian - 2004-12-14

    Logged In: YES

    Adding a symbol table for primitive types should be
    sufficient to check this.

  • Michael Tamm

    Michael Tamm - 2004-12-15

    Logged In: YES

    Why do we need type information?
    If the name on the left hand side of the assignment
    is the same as on the right hand side, you can
    always substitute a = a + ... with a += ...

    Or what do I miss here?

  • Lars Kühne

    Lars Kühne - 2004-12-15

    Logged In: YES

    The example in the javalobby article uses

    int a = 5;
    float b = 7.5;
    a += b;

    When checking the += assignment, the requested check should
    only trigger an error if there is actually loss of precision
    (here: cast from float to int). We need type information for
    the lhs and rhs of the assignment to determine if that is
    the case.

    Maybe I misunderstood feq2005, but a symbol table (that
    carries the type of each variable?) is not sufficient
    because you might come across more complex situations than
    in the simple example above. Consider

    int a = 5;
    a += (someMethodInSuperclass() * OtherClass.CONSTANT);

    Again, the check will need type information for the rhs. I
    don't see how such information can be obtained from a symbol
    table that is built only from syntactic information in the
    class that contains the offending code.

  • fengqian

    fengqian - 2004-12-15

    Logged In: YES

    Ok, I really meant a typing information. But a symbol table
    is the first step to type each node. A symbol table would
    have type information for local variables and fields and
    method return types. Based on that, we can type each AST
    node (expressions).

    It more sounds like a complete compiler now.

  • Roman Ivanov

    Roman Ivanov - 2016-06-25
    • status: open --> closed
    • Group: --> Future

Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:

No, thanks