I am trying to optimize my code, instead of using object Name in if else I want to pass the SObject parameter and combine below code

Instead of using separate objects I am trying to merge if else into one loop and pass the SObject parameter dynamically based on the object Name, how can I achieve that. Based on this, I'll have to use the similar logic and modify my queueable class, there is a lot of redundant code.. Please advice how to achieve this. Thanks.


This is more general points than a direct solution to your problem.

You can certainly write methods that accept the base type SObject and then use the get and set methods that all instances support to access and update field values. There are many other methods available too - see SObject Methods.

Custom objects all have these Custom Object Standard Fields. So you can rely on being able to read a custom object name like this:

SObject sob = ...;
String name = (String) sob.get('Name');

or set it like this:

String value = '...';
sob.put('Name', value);

and it is possible to hard-code other field names as strings, though they will all have API names that end in __c as that suffix is automatically added and must be used.

But sometimes it is worth moving away from strings to make use of SObjectField and SObjectType tokens. These are part of the access mechanism to get hold of describe information: detailed descriptions of SObjects and SObject fields.

When you have an SObject you can get its SObjectType via its getSObjectType() method. An Id also has a getSObjectType() method. So, for example, starting from an Id you can get a custom object's name like this:

Id customId = ...;
String name = (String) Database.query(''
    + ' select 'Name'
    + ' from ' + id.getSObjectType()
    + ' where Id = :customId'

So you can write non-type specific code. And where you need to do something type specific you can check the type and branch in your code accordingly:

if (customId.getSObjectType() == MyCustomObject__c.SObjectType) {


In response to the comment "how can I get the SObject name as Account in this":

for(SObject sob : sObjectSelector.selectByExternalID(allMasterChildIdSet, objectName)) {

it looks like you may already have it in the objectName variable. But if a different object type is returned:

for(SObject sob : ...) {

    // As a type object
    SObjectType type = sob.getSObjectType();

    // As a type name string
    String typeAsString = String.valueOf(type);
| improve this answer | |
  • Thank you so much for the answer @Keith.. just for my clarification could you please tell me how can I get the SObject name as Account in this-- for(SObject acc : sObjectSelector.selectByExternalID(allMasterChildIdSet, objectName)) – user62694 Apr 19 at 21:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.