Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Apex class behavior with Null instance of Sobject
/*
MyController cnt = new MyController();
cnt.tst.Name = 'test';
cnt.tst = null;
system.debug('Test outside: '+(cnt.tst.Name == null)); //Test outside: true
system.debug('Test outside: '+(cnt.tst == null)); //Test outside: true
system.debug('Test outside: '+json.serializepretty(cnt.tst)); //Test outside: null
cnt.myMethod(); //Throws null pointer exceptions
*/
public class MyController {
public Account tst{get;set;}
public MyController(){
this.tst = [Select Id, Name From Account limit 1];
}
public void myMethod(){
system.debug('Test inside: '+(tst.Name == null)); //Throws null pointer exceptions
system.debug('Test inside: '+(tst == null));
system.debug('Test inside: '+json.serializepretty(tst));
}
}
Owner
enreeco commented Feb 28, 2017 edited

If the Sobject member is nullified, outside the class the member still is accessible (even if null) while inside an instance method the same system.debug('Test inside: '+(tst.Name == null)); throws an exception

Some ref: http://salesforce.stackexchange.com/questions/135750/strange-behavior-with-null-sobject-in-apex-class but this does not explain why the member method fails

logontokartik commented Mar 13, 2017 edited

Yes, I noticed this behavior when writing Apex in the past, the way you can make this more controller is by using 'this' keyword., So in your myMethod() if you change to below, it should give you the same results as Execute Anonymous. SObjects have a behavior of throwing NPE if they are not initialized.

system.debug('Test inside: '+(this.tst.Name == null)); //Throws null pointer exceptions system.debug('Test inside: '+(this.tst == null)); system.debug('Test inside: '+json.serializepretty(this.tst));

Owner
enreeco commented Mar 13, 2017

@logontokartik in this context this.tst and tst refers to the same inner member, there are no other "tst" variables, how did you explain this regarding the Apex engine?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment