Search

Sunday 23 December 2012

Pass By Reference or By Value in Salesforce

You probably know all or most of this but try this

//If you want to know definitely what happens to references in SF run callRefs(); - http://shivasoft.in/blog/java/pass-by-value-and-pass-by-reference/

public static void callRefs(){
Boolean testbool = true;
integer testint=1;
Map<String,String> testmap1 = new Map<String,String>();
Map<String,list<String>> testmap2 = new Map<String,list<String>>();
Account acc = [Select BillingCountry From Account Limit 1];
Map<String,list<Error__c>> testmap3 = new Map<String,list<Error__c>>();
Map<String,set<String>> testmap4 = new Map<String,set<String>>();
testRefs(testbool, testint, testmap1, testmap2, testmap3, testmap4, acc);
system.debug('## testbool ' + testbool);
system.debug('## testint ' + testint);
system.debug('## testmap1 ' + testmap1);
system.debug('## testmap2' + testmap2);
system.debug('## testmap3' + testmap3);
system.debug('## testmap4' + testmap4);
system.debug('## acc ' + acc);
Error__c err2 = new Error__c(Class_Name__c='test2', SOQL_Queries__c=2);
list<Error__c> changelst = testmap3.get('testme');
changelst.add(err2);
testmap3.put('testme', changelst);
testRefs(testbool, testint, testmap1, testmap2, testmap3, testmap4, acc);
system.debug('## testmap3' + testmap3);
system.debug('## testmap4' + testmap4);
}
public static void testRefs(Boolean testbool, integer testint, Map<String,String> testmap1, Map<String,list<String>> testmap2, Map<String,list<Error__c>> testmap3, Map<String,set<String>> testmap4, Account acc){
testbool = false;
testint=2;
testmap1.put('test' , '1');
list<String> newlst = new list<String>();
newlst.add('1');
newlst.add('2');
testmap2.put('testme' , newlst);
acc.BillingCountry = 'Spain';
update acc;
list<Error__c> errlst;
if (testmap3.get('testme') == null){//if you remove this if something different will happen
Error__c err = new Error__c(Class_Name__c='test', SOQL_Queries__c=1);
errlst = new list<Error__c>();
errlst.add(err);
testmap3.put('testme', errlst);
}
set<String> newset = new set<String>();
newset.add('hi');
testmap4.put('test', newset);
}
Salesforce state
“In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This means that any changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments are lost.
Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This means that when the method returns, the passed-in argument still references the same object as before the method call, and can’t be changed to point to another object. However, the values of the object’s fields can be changed in the method.”