Certified Platform Developer II Exam QuestionsBrowse all questions from this exam

Certified Platform Developer II Exam - Question 42


trigger AssignOwnerByRegion on Account ( before insert, before update )

{

List accountList = new List();

for( Account anAccount : trigger.new )

{

Region__c theRegion = [

SELECT Id, Name, Region_Manager__c

FROM Region__c -

WHERE Name = :anAccount.Region_Name__c

];

anAccount.OwnerId = theRegion.Region_Manager__c;

accountList.add( anAccount );

}

update accountList;

}

Consider the above trigger intended to assign the Account to the manager of the Account's region.

Which two changes should a developer make in this trigger to adhere to best practices? (Choose two.)

Show Answer
Correct Answer: ABCD

To adhere to best practices, the developer should move the Region__c query to outside the loop to avoid repeated SOQL queries which can lead to performance issues (too many SOQL queries error). Additionally, in 'before' triggers, changes made to the records in trigger.new are automatically saved, so the update DML operation is redundant and should be removed.

Discussion

12 comments
Sign in to comment
sajjankrguptaOptions: BC
Dec 10, 2020

Using a SOQL query inside for loop is bad practice and since it is before insert/update no need to perform DML. Ans is B and C.

AB1993Options: BC
Aug 11, 2021

B & C is the correct answer

amerbearatOptions: BC
Aug 13, 2021

b and c is the answer as it is a before trigger we don’t need to update the account and soql always outside of the loop

PratibhadxOptions: BC
Oct 10, 2021

B & C obviously

ram12313Options: BC
Mar 27, 2023

B&C is correct if we're only talking about best practices. But we still need to tidy it up a bit like code below. trigger AssignOwnerByRegion on Account ( before insert, before update ) { Set<String> acctRegionNames = new Set<String>(); for( Account acc : Trigger.new){ acctRegionNames.add(acc.Region_Name__c); } Map<String, String> regionMap = new Map<String, String>(); for( Region__c reg : [SELECT Name, Region_Manager__c FROM Region__c Name IN :acctRegionNames]){ regionMap.put(reg.Name, reg.Region_Manager__c); } for( Account anAccount : trigger.new ){ if(regionMap.containsKey(anAccount.Name)){ anAccount.OwnerId = regionMap.get(anAccount.Name); } } }

Genki_SugisakiOptions: BC
Feb 26, 2023

B&C A is OK if Use a Map to cache the results of the Region__c query by Name

levianOptions: BC
Sep 29, 2022

B and C, for sure

Dean5555Options: BC
Oct 6, 2022

B&C it is

sf2022Options: BC
Dec 7, 2022

BC are correct answers

amilaveerOptions: BC
Dec 17, 2022

B & C are correc t

MetaLojiqTeeOptions: BC
Jul 30, 2023

B) Performing Queries inside a loop is not good practice, C) Changes made to records retrieved from 'Before' trigger context are automatically persisted if the trigger transaction completes successfully

Jeet89123Options: BC
May 29, 2024

B and C correct as per best parctices