Sub topic 18
Best practices and troubleshooting
This chapter assumes you can build formula fields and roll-up summary fields in Setup, and that you know the limits covered earlier. It collects the habits that prevent problems and a checklist for diagnosing the ones that still occur.
Best practices
- Guard every division. Test the divisor before dividing, as in
IF(Line_Item_Count__c = 0, 0, Total_Amount__c / Line_Item_Count__c). - Choose the blank-handling option on purpose. When you save a formula, you pick whether blank number fields are treated as zero or as blank. Use
BLANKVALUEwhen only one field needs a default. - Keep formulas short. Split a long formula into helper formula fields. This avoids the compiled-size limit and makes each piece easier to test.
- Prefer
CASEover nestedIFwhen you compare one field to several values. - Filter roll-ups at the source. Use filter criteria on the roll-up instead of adding a second formula to exclude records.
- Plan for the roll-up limit. An object has a small fixed number of roll-ups. Reserve them for values you report on often.
- Load data in parent order. When you bulk load child records, sort them by master record. This reduces row-lock contention.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| `#Error!` in a formula field | Division by zero or an invalid operation on a blank | Add an `IF` guard or `BLANKVALUE` |
| "Compiled formula is too big" | Too many cross-object references or too much nesting | Move parts into helper fields |
| Roll-up total looks stale after you change filter criteria | Existing values are not recalculated automatically | Use the field's **Mass Recalculate** option |
| `UNABLE_TO_LOCK_ROW` during a load | Child updates lock the master record | Group rows by master and reduce batch parallelism |
| "Field is not writeable" in Apex | You tried to set a formula or roll-up field in DML | Remove the assignment and re-query the value |
| Formula is not available in a roll-up | The formula uses cross-object references or `TODAY` or `NOW` | Roll up a stored field instead |
100%
Reading the saved value in code
A new record has no calculated value until it is saved. Re-query it, as in this example:
Invoice__c inv = new Invoice__c(Name = 'INV-001');
insert inv;
Invoice__c saved = [SELECT Id, Total_Amount__c FROM Invoice__c WHERE Id = :inv.Id];
System.debug(saved.Total_Amount__c);Exercise
A formula field Average__c divides a roll-up total by a roll-up count. It shows #Error! on some invoices. What is the cause and the fix?
Show answer
Invoices with no line items have a count of 0, so the formula divides by zero. Wrap the division in an IF that returns 0 when the count is 0: IF(LineItemCount_c = 0, 0, TotalAmount_c / LineItemCount_c).