Software Engineering for Smart Data Analytics & Smart Data Analytics for Software Engineering
“The code performs an increment operation (e.g., i++) and then immediately overwrites it. For example, i = i++ immediately overwrites the incremented value with the original value. ” – 2013-10-14
Java offers pre- and postfix incrementation operators ++i and i++ that can be used to shorten the code. In the case of prefix operators the value of the variable is changed immediately. A postfix operator on the other hand processes the unchanged value of the variable and updates it afterwards. E.g. a=i++; results in a being assigned i and i getting incremented right after. Curiously in Java i=i++ behaves in the same way; i is assigned i. Obviously this behavior is not intuitive since one would expect the incrementation to happen.
This comes from the internal implementation of the operator. The value is changed immediately while the old one gets remembered and used to process the term. Hence i gets incremented at first but then the old remembered value is assigned right afterwards.
The problem must be detected no matter what type of variable is incremented (field, local var, or parameter):
<code Java> public class OverwrittenIncrement {
private int f; public void overwrittenIncrementOfField() { f = f++; } public int overwrittenIncrementOfLocalVar() { int l = 42; l = l++; return l; } public int overwrittenIncrementOfParameter(int p) { p = p++; return p; }
} </Code>
The solution is straightforward. Replace the nonsense expression i=i++ by i++.
<code Java> public class OverwrittenIncrement {
private int f; public void overwrittenIncrementOfField() { f++; } public int overwrittenIncrementOfLocalVar() { int l = 42; l++; return l; } public int overwrittenIncrementOfParameter(int p) { p++; return p; }
} </Code>