Skip to content

Instantly share code, notes, and snippets.

@enreeco
Last active March 13, 2017 19:02
Show Gist options
  • Save enreeco/464e0c04db7d88ab188e5bfa1022e9ce to your computer and use it in GitHub Desktop.
Save enreeco/464e0c04db7d88ab188e5bfa1022e9ce to your computer and use it in GitHub Desktop.
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));
}
}
@enreeco
Copy link
Author

enreeco commented Feb 28, 2017

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
Copy link

logontokartik commented Mar 13, 2017

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));

@enreeco
Copy link
Author

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