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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With