Inefficient calls to Schema.getGlobalDescribe().get()
Why is this an issue?
Schema.getGlobalDescribe() retrieves metadata for every object in the Salesforce org, which is a resource-intensive operation. Using Schema.getGlobalDescribe().get(objectName) to look up a single SObjectType loads the entire global describe map just to retrieve one entry. A more efficient alternative is Type.forName(), which resolves the type directly without loading all object metadata. This rule applies to both Apex classes and triggers.
Examples
Example of incorrect code:
public static Schema.SObjectType getType(String objectName) {
// Loads metadata for all objects just to retrieve one
Schema.SObjectType soType = Schema.getGlobalDescribe().get(objectName);
return soType;
}
Example of correct code:
public static Schema.SObjectType getType(String objectName) {
// Resolves the type directly without loading all metadata
Schema.SObjectType soType = ((SObject) Type.forName(objectName).newInstance()).getSObjectType();
return soType;
}
How can I fix violations?
Replace Schema.getGlobalDescribe().get(objectName) with ((SObject) Type.forName(objectName).newInstance()).getSObjectType(). This rule supports autofix, which applies this replacement automatically.
If this pattern appears in multiple places, consider extracting it into a utility method to improve readability.
Note that Type.forName() returns null if the type name cannot be resolved β for example, if it is invalid, or refers to a non-global class in a managed package. If you chain .newInstance() directly onto a null result, Apex will throw a NullPointerException. If your code needs to handle unresolvable types, add a null check:
public static Schema.SObjectType getType(String objectName) {
Type t = Type.forName(objectName);
if (t == null) {
return null;
}
return ((SObject) t.newInstance()).getSObjectType();
}
When should I disable this rule?
You may dismiss specific violations when you genuinely need to iterate over all objects in the org and there is no alternative approach.
Resources
