Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
    
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 at 15:18
up vote 6 down vote accepted

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.

share|improve this answer
    
That looks great. Just what I was looking for. – LeeFranke Feb 17 at 15:36
    
@LeeFranke Also, vote on success.salesforce.com/ideaView?id=08730000000cGGlAAM and success.salesforce.com/ideaView?id=08730000000DjPQAA0. This would eliminate the need for such a function. – sfdcfox Feb 17 at 16:02
    
@sfdcfox Ha nearly everyone who voted for it is a member here. You're noticeably missing from the list! – Adrian Larson Feb 17 at 16:04
    
@AdrianLarson Actually, I had created one of the ideas... I just found the other one. I've submitted a merge request, and I'll vote on the other. – sfdcfox Feb 17 at 16:08
    
@sfdcfox Right, forgot you're Brian Fear...I was thinking it sounded familiar. Never mind then, carry on! – Adrian Larson Feb 17 at 16:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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