A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/pmd/pmd/issues/2973 below:

UnnecessaryBoxing · Issue #2973 · pmd/pmd · GitHub

Proposed Rule Name: UnnecessaryBoxing (pmd7)

The rule "PrimitiveWrapperInstantiation" has been implemented for PMD 6.37.0.

Proposed Category: Best Practices

Description:
The new rules that merges together:

(all in category performance)

The first rule flags valueOf calls, and only cares about primitive wrappers that are created and unboxed explicitly in the same expression, like Integer.valueOf(0).intValue(). This is contrived and no one does it: the rule has zero violations in checkstyle, spring, or the jdk.

The other rules flag uses of the constructors of primitive wrappers (but for some reason not Double, Character or Float). The rationale is that using valueOf may avoid creating a new instance. This is true, but also,

So the idea is to merge all those into a new UnnecessaryBoxing rule that cares about:

The new rule PrimitiveWrapperConstructor cares about:

This applies to all primitives.

Code Sample: This should include code, that should be flagged by the rule. If possible, the "correct" code
according to this new rule should also be demonstrated.

class Scratch {

    public static void main(String[] args) {

        Integer anInteger = 2; // ok
        
        Object a = Integer.valueOf(2);  // explicit boxing where the value would be autoboxed
        int b = anInteger.intValue();     // explicit unboxing where the value would be auto-unboxed
        Object c = anInteger.intValue();  // unboxing where the value is immediately reboxed
        int i = Integer.valueOf(0);     // boxing where the value is immediately unboxed
        
        Integer.valueOf(anInteger);       // boxing of already boxed value
        
        if ((boolean) Boolean.TRUE);    // Casts that unboxes the operand        
        
        // Actually a cast to a wrapper can be treated just like a valueOf call
        // (when the cast operand is primitive) and be handled exactly like a valueOf call,
        // so be handled in all the situations above.
        
        Integer o = (Integer) a; // a is an Object so the cast is not redundant
    }
}

Possible Properties:

None that I can think of.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4