Do you remember PEMDAS from Algebra class? If not, that’s okay. I wiped my memories from that time period too. Anyways, PEMDAS defines the order in which operators are processed in multi-operator expressions.
Apex enforces the same concept. Sometimes you’ll need to build a complex equation in Apex to meet your business needs. Having a consistent order of operations provided by Apex dictates which part of the equation is calculated first.
For example, let’s say you’re trying to calculate your Total Contract Value (TCV) in Apex for both recurring and nonrecurring revenue.
You’d probably have variables like these already set up:
Integer monthlyRecurringRevenue = 3000; Integer nonRecurringRevenue = 2000; Integer contractLengthMonths = 36;
To calculate your contract value you’ll need to find the product of your contract length and monthly recurring revenue then add that to any nonrecurring revenue.
Your code would look something like this:
Integer monthlyRecurringRevenue = 3000; Integer nonRecurringRevenue = 2000; Integer contractLengthMonths = 36; Integer totalContractValue = nonRecurringRevenue + contractLengthMonths * monthlyRecurringRevenue;
Our formula works as is because *
takes higher precedence than +
. So Apex will automatically perform contractLengthMonths * monthlyRecurringRevenue
and then add that to the nonRecurringRevenue
.
Optionally, we could add parentheses to make this more clear.
Integer totalContractValue = nonRecurringRevenue + (contractLengthMonths * monthlyRecurringRevenue);
The outcome is the same, but In my opinion, adding the parenthesis is a small detail that makes the code clearer.
Let’s look at one more example:
Integer mysteryInteger = 3 * (5 + 3) + (9-1) / 4; // Break down: // 1) 3 * (8) + (9-1) / 4; // 2) 3 * (8) + (8) / 4; // 3) 24 + (8)/4; // 4) 24 + 2 // 5) 26
Here’s the difference adding parentheses would have made to the outcome:
Integer mysteryInteger = (3 * (5 + 3) + (9-1)) / 4; // Break down: // 1) (3 * (8) + (9-1)) / 4; // 2) (3 * (8) + (8)) / 4; // 3) (24 + (8))/4; // 4) (32)/4 // 5) 8
The full breakdown of Apex operator precedence can be found here. There’s a lot in that article, here is the precedence based on the operators we’ve learned so far:
1)Parenthesis
2)Multiplication/ Division
3)Addition/ Subtraction