1

Is there any benefit of getting sobject type using

Schema.getGlobalDescribe().get('Lead');

instead of

 Lead.sObjectType;

Also what is the benefit of using 3 char prefixes of known IDs like Id valueId = '00Q......; instead of Id.getSobjectType method?

2

In the first question, Schema.getGlobalDescribe().get('Lead'); is used when you have a object Name as String and you want to create an instance of SObjectType.

If you already have specific SObject Id then from the Id we can get SObjectType using leadId.getSObjectType()

Performance wise, first option is much slower than 2nd option.

You can refer my blog for more details. Efficient way of dynamically casting SObject to Specific Object to update records

1

If you are writing code where the SObject type is known, the code is compile time checked and also easier to read if you reference the type directly i.e.:

SObjectType t = Lead.sObjectType;

or:

Lead l = ...;
String company = l.Company;

Note that an Id has a getSObjectType() method so that is cleaner to use that than looking at the first 3 characters of the Id.

The 3 character key prefix can be found if you really need it using:

SObjectType t = Lead.sObjectType;
String prefix = t.getDescribe).getKeyPrefix();

Only use the more dynamic style of code when you have to e.g. when you are writing code designed to work with multiple types of SObject or where the concrete type is not available at compile time.

PS

Another factor relating to managed packages is whether you want to couple your code to objects that require a more expensive license. Using the dynamic style (and politely failing if the object isn't available) allows your managed package to work with or without the licensed objects.

  • I do prefer using Lead.sObjectType but does Salesforce puts license constraints when using Lead.sObjectType Opportunity.sObjectType expressions or on field expression when checking accessibility in managed package? – pklochkov Apr 15 at 8:29
  • 1
    @pklochkov I added a PS on that subject. I can't detail the specific consequences (because I don't know them), but the dynamic style is the choice we have made for this situation. – Keith C Apr 15 at 9:21
  • 1
    The main license types that can't access Lead and Opportunity would be Salesforce Platform, right? But if an org contains only those license types it typically comes with one admin license that can see CRM objects but is contractually obligated not to use them. In any case that license is still able to install packages that have CRM object dependencies, as long as end-users don't do anything that interacts with those objects. – Charles T Apr 15 at 12:13

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.