Disorder PMD

I have the following Java method:

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

PMD complains about this code in violation of "Useless partners."

I reviewed the operator bias rules , and I still don't see extra parentheses in this code. Did I miss something?

+5
source share
2 answers

There is no extra bracket in this code, as you can see if you are running 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)); 

In addition, it is sometimes useful to add extra brackets for readability. For instance:

 int i = x << y + z; // this will shift x by y+z bits int j = x << (y + z); // equivalent, but more readable 
+5
source

After reading the operator’s settings, the line of code, and the PMD warning, this is probably one of those rare cases where priority should be applied as

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

but not

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

You are right, and brackets are not superfluous. Removing them will make the code less readable, and each of them is necessary. In fact, this whole question is worthy of xkcd comic

+3
source

Source: https://habr.com/ru/post/1241079/


All Articles