[SalesForce] Better way to test for null

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');
     else
        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?

Best Answer

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.