Curious behavior: Specialization of sObjects on Salesforce

As you may know at this point, I’ve been working with Salesforce Development for a while now, and the more I learn about it, the more interested I become in learning more. I see it as a healthy cycle of improvement.

During this process I got amazed about how flexible sObjects are, and how they represent Salesforce records and their fields. Trailhead is our friend:

Each Salesforce record is represented as an sObject before it is inserted into Salesforce. Likewise, when persisted records are retrieved from Salesforce, they’re stored in an sObject variable.
Standard and custom object records in Salesforce map to their sObject types in Apex. Here are some common sObject type names in Apex used for standard objects.

  • Account
  • Contact
  • Lead
  • Opportunity

And because sObjects were engineered this way, a Generalization of shared characteristics from two or more classes, the concept of Specialization are also applied in our Apex code:

Specialization means creating new subclasses from an existing class. If it turns out that certain attributes, associations, or methods only apply to some of objects of the class, a subclass can be created.

And they are, for all objects derived from sObjects. Therefore, we could have a code like this:

Please note that the Account object is being “converted” from a SObject (cast). Or maybe we could apply the same concept, but now using a Custom Object:

Unfortunately, sometimes Salesforce’s Apex compiler does not complain when we mess up with these specializations, and we must be careful, depending on the logical scope.

Take this diagram, as an example. Since the lists of Accounts and CustomObjects are actually lists of sObjects, you could call the same method passing both lists as a parameter:

And this code would compile:

For curiosity, if you uncomment the for loop at line 7, you’ll get an error, because now you’re trying to access the object field’s content.

So, at least in Salesforce Summer ’17 version that’s how it works. I’m not sure if Salesforce considers that as the right behavior – that it is working as intended – or if they’re going to change it in future versions. Meanwhile, just be careful with how you use it and you’ll be fine.

That’s all folks. See you next time.