Object values and local values in arithmetic

So I was trying to perform a simple arithmetic on values within and object 'currentUser' in my one 'pricingAction' class.

The code should add the two volume values(doubles) and set the value of the variable to the sum of the two. In this example the volume_2, and volume_4 variable should be set to the sum of the two.

method 1:

if(filled4 == true){
    if(currentUser.getUtility_2().equalsIgnoreCase(currentUser.getUtility_4())){
        currentUser.setVolume_2(currentUser.getVolume_2() + currentUser.getVolume_4());
        currentUser.setVolume_4(currentUser.getVolume_2() + currentUser.getVolume_4());
    }
}

method 2:

if(filled3 == true){
    if(currentUser.getUtility_2().equalsIgnoreCase(currentUser.getUtility_3())){
        holder = 0;
        holder = currentUser.getVolume_2() + currentUser.getVolume_3();
        currentUser.setVolume_2(holder);
        currentUser.setVolume_3(holder);
    }
}

Method 2 returns the value expected and Method 1 appears to be tossing in a duplicate of the value it is setting to.

My question is why does Method 1 do this? I can only assume it is just tacking on the extra sum to the current value but the setter method is a generic this.x = x;

Jon Skeet
people
quotationmark

Let's simplify the code a little so it's easier to read:

foo.setX(foo.getX() + foo.getY());
foo.setY(foo.getX() + foo.getY());

Now suppose we start with foo.X = 10, foo.Y = 20.

The first statement will initially compute foo.X + foo.Y - which is 10+20, or 30. It then sets that (30) as a new value for foo.X.

The second statement will initially compute foo.X + foo.Y, which is now 30+20, or 50. Note that this is using the new value of foo.X. It then sets 50 as a new value for foo.Y.

If you want to set the same value for both properties, you should compute that value once, to avoid the change to the value of the first property from affecting the computation. However, it's clearer to declare the local variable for that value as locally as you can:

double result = foo.getX() + foo.getY();
foo.setX(result);
foo.setY(result);

That's not only correct, but it's also easier to understand and more efficient. Bonus!

people

See more on this question at Stackoverflow