Yesterday I got rejected from a job interview because the interviewer asked me to write a trigger to limit the number of contacts per account and I wrote exactly the below but he said this won't work and it is not the correct way to write the same. I ran the same and it is working fine I am not able to see any problem with the below code can someone please help me understand from the interview's perspective why he said this is not the right way.
trigger ContactTrigger on Contact (after insert, before Insert, before update, after update) {
if(Trigger.operationType == triggerOperation.AFTER_INSERT || Trigger.operationType == triggerOperation.AFTER_UPDATE) {
set<Id> IdSet =new set<Id>();
for(Contact cot : trigger.new) {
if(cot.accountID != null) {
IdSet.add(cot.accountId);
}
}
Integer contactListCount = [Select count() from contact where accountID IN: IdSet];
if(contactListCount > 2) {
for(contact cop : trigger.new) {
cop.addError('cannot have more than 2 contacts per account');
}
}
}
}