Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

#270 Warn for unboxing

open
William Pugh
3
2012-07-02
2012-06-04
Andreas Ottiger
No

A bug pattern to detect all auto unboxings.

e.g. in the following case:

class Test {
private Integer value;

public int getValue() {
return value;
}
}

To clarify, I know that the compiler can report both auto boxing and unboxing. Howevern I'd like to have a warning when auto unboxing only.

Discussion

  • William Pugh
    William Pugh
    2012-07-02

    You need to provide a better explanation for why this should be reported as a bug pattern.

     
  • William Pugh
    William Pugh
    2012-07-02

    • priority: 5 --> 3
    • assigned_to: nobody --> wpugh
     
  • Why is this a bug pattern?

    Autoboxing and unboxing allows a mixing of primitive types and the boxed Integer. An int can always be boxed into an Integer, so there is nothing dangerous about auto boxing.

    However, the auto unboxing can lead to a NPE (as in the example provided). If the programmer is not aware that an auto unboxing will happen at some point (e.g. the programmer writing the "getValue()" method in the example), he probably won't think of a necessary null check.

    A typical example is when reading from a database. Queries return typically objects (as the database allows for null values). A data access method might have the signature

    public Long getPrice(long itemNr);

    Somewhere later in the processing you there can be code like

    long basePrice = getPrice(...); // auto unboxing happens
    doSomething(basePrice);

    And this is very prone to lead to NPE, as the price might be null. The correct way might be
    Long basePrice = getPrice(...);
    if (basePrice == null) ... handle exceptional case ...
    else doSomething(getPrice(...).longValue());

    There is no way of finding the code, where the auto unboxing will happen. There is a compiler switch to mark auto boxing AND unboxing as warning, however the auto boxing is quite ok and should not be marked.