4

I started learning about Execution Context and I got this question:

Let's say I have a static sObject variable in the beginning of my Execution Context filled by a select. In the middle of the execution, I update a custom field of this sObject. If I get the value at the end of the Execution Context, which value do I get? The new one (even though I haven't selected it again) or the old one?

Thanks.

1 Answer 1

5

You will get the updated version, assuming you modified that sObject.

sObject s = [SELECT Id FROM sObject];
s.put('SomeField__c', 'new_value');
update s;
System.assertEquals('new_value', s.get('SomeField__c'));

As long as you modified and did your "update" using the original sObject, then all's well... insert and update work by doing the action, then returning the results right back to your original variable (for example, when you do an insert, you get the exact same object back in it's place PLUS the new Id that was just assigned/created)

sObject s = new sObject();
System.assertEquals(null, s.get('Id'));
insert s;
System.assertNotEquals(null, s.get('Id'));
3
  • 2
    Shouldn't the s.put('SomeField__c', 'new_value'); not require an update after to still hold the value at the end of the execution since it's still the same context?
    – dphil
    Apr 14, 2015 at 21:04
  • 1
    when we say execution context, the value of static variable would be retained, no need for insert/ update statements. However, as soon as execution context is completed, the variable is collected (refer: Garbage collection) and the values are lost, unless it was saved before closing execution context.
    – Anshul
    Apr 14, 2015 at 21:09
  • 1
    correct @dphil, no need to update to hold the value... i was inferring (maybe incorrectly) the OP was asking whether he had to re-query the information at the end (implying the change was committed in some fashion during the context)... but with or without the update, a static sObject will hold whatever values are applied to it so long as it's not later overwritten with another query result or new sObject() Apr 14, 2015 at 21:15

You must log in to answer this question.

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