Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 992
Stu Thompson Avatar asked Dec 18 '25 03:12

Stu Thompson


2 Answers

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.

like image 126
Joachim Sauer Avatar answered Dec 20 '25 17:12

Joachim Sauer


Depending on what IDE you use, if it does syntax highlighting, I would modify the highlighting so that it looks for the pattern =+ and makes it some awful-to-look-at color.

like image 27
Matt Bridges Avatar answered Dec 20 '25 16:12

Matt Bridges



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!