September 30, 2016 by LanceShi
2.4 Variables only store data
A variable is a container of a small piece of information. And it only remembers the value of that information. It doesn’t know know how is that value generated or where it is coming from. This concept might seem easy, but it is worth taking some time really understanding it. Here is a sample code.
Integer price = 0; Integer salesTax = price * 0.09; Integer totalAmount = price + salesTax; price = 200; System.debug(salesTax); System.debug(totalAmount);
What should be the value of salesTax and totalAmount in the debug output?
The correct answer is they are both zero.
A bit explanation
Some might find the result very easy to understand. And some are not. Please note, the variable salesTax only remembers its current value, which is 0 – 0 * 0.09. It doesn’t know it is price * 0.09. It is not an equation or function or anything like that. It is just a value. If you want to get the salesTax of a new product, you need to recalculate.
If you want something to hold a formula, you need to use function (method), which will be introduced in the next chapter. But for now, please keep that in mind – variables only hold values.
- If you remove the = 0 in the 1st line of the sample code. Leaves only Integer price, what will happen?
- Move the calculation code lines of salesTax and totalAmount and calculate the them after the price has been changed.