Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PMD UselessParentheses violation

Tags:

java

pmd

I have the following Java method:

private int calculate() {
    return (bytes[0] & 0xff) + ((bytes[1] & 0xff) << 8);
}

PMD complains on this code with "UselessParentheses" violation.

I've reviewed operator precentence rules and I still don't see redundant parentheses in that code. Am I missing something?

like image 785
Michal Kordas Avatar asked Jan 20 '16 21:01

Michal Kordas


2 Answers

There's no unnecessary parenthesis in this code, as you can see if you run this:

        byte [] bytes = new byte[] {1,2};

        System.out.println( (bytes[0] & 0xff) + ((bytes[1] & 0xff) << 8));
        System.out.println( bytes[0] & 0xff + ((bytes[1] & 0xff) << 8));
        System.out.println( (bytes[0] & 0xff) + (bytes[1] & 0xff) << 8);
        System.out.println( (bytes[0] & 0xff) + (bytes[1] & 0xff << 8));

Moreover, sometimes it's actually good to add extra parentheses for readability. For example:

int i = x << y + z;   // this will shift x by y+z bits
int j = x << (y + z); // equivalent, but more readable
like image 66
biziclop Avatar answered Sep 21 '22 19:09

biziclop


After reading the operator preferences, the line of code, and the PMD warning, this is probably one of those rare cases where the precedence is meant to be applied like

PMD complains on this code with a useless (parenthesis warning)

rather than

PMD complains on this code with a (useless parenthesis) warning.

You're code is right, and the parenthesis aren't superfluous. Removing them would make the code less readable, and every one of them are needed. In fact, this whole issue is worthy of a xkcd comic

like image 31
Edwin Buck Avatar answered Sep 23 '22 19:09

Edwin Buck