Last active
March 13, 2017 19:02
-
-
Save enreeco/464e0c04db7d88ab188e5bfa1022e9ce to your computer and use it in GitHub Desktop.
Apex class behavior with Null instance of Sobject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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)); | |
} | |
} |
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));
@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
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 exceptionSome 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