9

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?

Michal Kordas
  • 10,475
  • 7
  • 58
  • 103
  • Remove parentheses in this block: (bytes[0] & 0xff) – eg04lt3r Jan 20 '16 at 21:54
  • 10
    Crucially, even if there was a superfluous pair of parentheses (I can't see any), the code would be far less readable without it. The way this is written conveys exactly what your logic is meant to do. – biziclop Jan 20 '16 at 21:55
  • Sorry, my mistake, delete parentheses in (bytes[0] & 0xff). Or you can add suppress warning for PMD to this method. – eg04lt3r Jan 20 '16 at 21:57
  • @eg04lt3r `+` also has precedence over `&`, `bytes[0] & 0xff + ...` is equivalent to `bytes[0] & (0xff + ...)`, not `(bytes[0] & 0xff) + ...`. – azurefrog Jan 20 '16 at 21:59

2 Answers2

9

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
biziclop
  • 48,926
  • 12
  • 77
  • 104
  • 1
    FYI: This has been fixed with PMD 5.3.5 ([bug #1407](https://sourceforge.net/p/pmd/bugs/1407)). So - updating PMD should get rid of this false violation. – adangel Jan 28 '16 at 21:04
5

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

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138