I've got an AggregrateResult that has several SUMs in it like this:

Select SUM(Optical__c) HWOpti,SUM(Tcal__c) TCal, SUM(POS__c) POSHWOpt

Each of those fields are of currency. So I want to then do some calculations.

So I do this for each SUM result first:

HWOpti_a = (double) results.get('HWOpti');

If the SUM result is null then the resulting conversion to double results in a null. Then the calculation fails and throws and error.

So I just did a bit of null checking for each SUM result like this:

    if(results.get('HWOpti') != null)
        HWOpti_a = (double) results.get('HWOpti');
        HWOpti_a =0;

It works but it seems a bit messy. Is there a better way to check for the null or make sure that the SUM results in at least a zero even if all the values summed are null?

  • Unless your data is populated with zeros instead of nulls, that's going to happen when the aggregrate results are calculated. About the only other method is to use a try-catch block to capture the null pointer exception that would occur from trying to access the null value. You're doing what's necessary. – crmprogdev Feb 17 '16 at 15:18

A common strategy for this is to write a method called elide. It can be written for Integer, Decimal, Long, etc. as well.

public static Double elide(Double input)
    return (input == null) ? 0 : input;

It seems simple but this syntactic sugar really helps, especially if you are using values inline in your calculations.

Double c2 = elide(a2) + elide(b2)

If you would like to see this feature included natively in Apex, vote for this idea by @sfdcfox.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.