0

Is there a way or any method (other than write a long helper for each object) that could initialize all objects within an object even if the JSON was not received aka:

@AuraEnabled
public SomeObject objectHere;

I would want this to be automatically substantiated with an empty version of that object so when I go objectHere.id I don't have to null check the object then the field.

3 Answers 3

3

You can use the Safe Navigation Operator (?.) to avoid null checks:

String someValue = inputParam?.objectHere?.someProperty;

This is likely the best choice in many cases, unless you need to actually use the object for output, then you might want to go with Derek's answer.

3
  • wait what where have these been all my life!? I didn't know these were actually implemented I just heard ages ago that salesforce were thinking on adding them Oct 21, 2021 at 15:52
  • 1
    @KarlLivesey You'd be forgiven for not knowing about them, they literally only came out just three releases ago. I actually helped fix a critical bug with it while it was in preview in Winter '21. It's helped me clean up a LOT of really ugly code. Also, you might have missed this gem as well (greater-/less-than now return false with a null value instead of throwing NullPointerException).
    – sfdcfox
    Oct 21, 2021 at 15:57
  • my only other dream would be for lists it would end the for loop if null so like: for(Account Acc : AccList){ } Oct 21, 2021 at 16:05
3

I don't believe there is a way to initialize class variables without writing code to explicitly set those variables.

That's not just a JSON deserialization thing, though JSON deserialization makes things just a bit more difficult because it doesn't run any constructors for the type you're using.

You could turn your class variables into properties and take advantage of your ability to specify a getter to do lazy initialization.

Anonymous apex example:

public class LazyLoadVars{
    public Account myAcc {
        get{
            if(myAcc == null){ myAcc = new Account(); }
            return myAcc;
        }
        set;
    }
}

LazyLoadVars llv = new LazyLoadVars();
// Also works when deserializing from JSON
//LazyLoadVars llv = (LazyLoadVars)JSON.deserialize('{}', LazyLoadVars.class);

llv.myAcc.Name = 'Success!';

system.debug(llv);

I'm not sure if I would recommend such an approach, however. I get a dirty feeling when I read this that I can't quite put my finger on.

1
  • yeah this feels wrong =/ Oct 21, 2021 at 16:07
2

No, there is nothing out of the box for this requirement. You'll need to roll your own initializer.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .