A developer must modify the following code snippet to prevent the number of SOQL queries issued from exceeding the platform governor limit. public class without sharing OpportunityService( public static List getOpportunityProducts(Set opportunityIds){ List oppLineItems = new List(); for(Id thisOppId : opportunityIds){ oppLineItems.addAll([Select Id FROM OpportunityLineItems WHERE OpportunityId =
:thisOppId)]; } return oppLineItems; } }
The above method might be called during a trigger execution via a Lightning component. Which technique should be implemented to avoid reaching the governor limit?
A. Use the System.Limits.getQueries() method to ensure the number of queries is less than 100.
B. Use the System.Limits.getlimitQueries() method to ensure the number of queries is less than 100.
C. Refector the code above to perform the SOQL query only if the Set of opportunityIds contains less 100 Ids.
D. Refactor the code above to perform only one SOQL query, filtering by the Set of opportunityIds.
B. Use the System.Limits.getlimitQueries() method to ensure the number of queries is less than 100.
Explanation:
The current code performs a SOQL query inside a loop, which can easily exceed the governor limit of 100 queries per transaction. This is a common anti-pattern in Apex.
Refactor to use a single SOQL query
The best practice is to bulkify the code by querying all OpportunityLineItems in one SOQL statement using the IN keyword:
public class without sharing OpportunityService {
public static List getOpportunityProducts(Set opportunityIds) {
return [SELECT Id FROM OpportunityLineItem WHERE OpportunityId IN :opportunityIds];
}
}
This approach uses 1 SOQL query, regardless of how many Opportunity IDs are passed in.
It ensures governor limits are not exceeded, even in bulk operations.
Why the other options are incorrect:
A. Use System.Limits.getQueries()
This checks how many queries have been used, but doesn't prevent the issue—just monitors it.
B. Use System.Limits.getLimitQueries()
This gives the total limit (typically 100), but again, doesn’t avoid SOQL-in-loop problems.
C. Limit logic to Sets with <100 IDs
This doesn't help. Even with <100 IDs, if you run 1 SOQL per ID, you still risk hitting the limit in other parts of the transaction.