javaoperatorscompound-operator

Automatically catching the use of =+ rather than += in Java


I have this horrible habit of typing the below and not catching it until well into testing:

int i = 1;
int j = 2;
i =+ j;  //i equals 2, not 3 as intended; assign only, + is unary and works on the j

The correct version, of course, would be

int i = 1;
int j = 2;
i += j;  //i equals 3, as intended with additive & assignment compound operator

I have made this mistake a zillion times. It would not surprise me of there is some code out there with a bug in it that escaped a test case. There has just got to be a way to prevent this systematically. Any ideas?


Solution

  • Regularly use tools like PMD and/or Checkstyle. Ideally as part of your build process/continuous integration.

    You might have to define a custom rule for this, because I don't know if any of those tools recognizes this as a problem by default.

    This will not only catch this problem, but also hint at a lot of other potential problems as well.