Plat-Dev-301 practice question 2 of 10

The Account object has a field, Audit_Code__c, that is used to specify what type of auditing theAccount needs and a Lookup to User, Auditor__c, that…

Full set: 160 questions

The Account object has a field, Audit_Code__c, that is used to specify what type of auditing the

Account needs and a Lookup to User, Auditor__c, that is the assigned auditor. When an Account is

initially created, the user specifies the Audit_Code__c. Each User in the org has a unique text field,

Audit_Code__c, that is used to automatically assign the correct user to the Account's Auditor__c

field.

Trigger:

Java

trigger AccountTrigger on Account (before insert) {

AuditAssigner.setAuditor(Trigger.new);

}

Apex Class:

Java

public class AuditAssigner {

public static void setAuditor(List<Account> accounts) {

for (User u : [SELECT Id, Audit_Code__c FROM User]) {

for (Account a : accounts) {

if (u.Audit_Code__c == a.Audit_Code__c) {

a.Auditor__c = u.Id;

}

}

}

}

}

What should be changed to most optimize the code's efficiency?

Answer options
A:

A. Add a WHERE clause to the SOQL query to filter on audit codes.

Correct answer
B:

B. Build a Map<String, List<Account>> of audit code to accounts.

C:

C. Build a Map<Id, List<String>> of Account Id to audit codes.

D:

D. Add an initial SOQL query to get all distinct audit codes.

Correct Answer:
A. A. Add a WHERE clause to the SOQL query to filter on audit codes.
Explanation

The provided code is highly inefficient because it queries for every User in the org and then uses a nested loop to compare them against the incoming Accounts. This can easily exceed CPU time limits. The most significant optimization is to make the SOQL query selective. By first collecting the AuditCodec values from the incoming accounts into a Set, a developer can add a WHERE AuditCodec IN :codeSet clause to the SOQL query. This drastically reduces the number of records returned and processed, directly addressing the primary performance bottleneck.

Why Incorrect

B. Building this map is a useful step in an optimized solution, but it doesn't fix the core problem of the non-selective SOQL query that fetches all users.
C. This map structure is not logical for solving the problem of assigning an auditor based on an audit code.
D. This is part of the correct pattern, but option A is more direct and describes the most critical optimization: filtering the SOQL query itself.

References

1. Apex Developer Guide, "Best Practices for Triggers", Section: "Bulkify Your Code". The guide emphasizes writing queries that are selective.

2. Apex Developer Guide, "Writing SOQL Queries", Section: "Filtering Query Results with the WHERE Clause".

3. Salesforce Architects, "Record-Triggered Automation", Section: "Apex Trigger Best Practices", Guideline: "One Trigger Per Object" and "Bulkify your Helper Methods" which includes writing selective SOQL.

Scroll to Top