I have a question relating to the best practices when coding a trigger.
I have already read up a fair bit on the best practices and understand the one trigger per object pattern, as well as the helper class pattern to move logic away from the trigger.
My question is - what should we do when we have multiple actions for an object where each of these actions affects multiple other objects?
Example: Using Case, Account and a custom object OBJECTABC.
OBJECTABC has a reference to Account but not to Case. There can be many OBJECTABC per Account.
We have the following two business rules that need to be implemented using a trigger:
SET LAST CASE UPDATED ON ACCOUNT AND OBJECTABC
Whenever a Case of type "FEEDBACK" is inserted or updated, it should also set the field "LastCaseUpdated" on the cases Account to the date that the Case was updated. It should also set the field "LastCaseUpdated" on OBJECTABC.
INCREASE THE CASE COUNT ON ACCOUNT AND OBJECTABC
Whenever a Case is inserted and it is of type "ENQUIRY", it should also increase the field "NumberOfCases" on the cases Account by one. It should also increase the field "NumberOfCases" on OBJECTABC.
SO WHICH PATTERN TO USE?
I would like to retrieve the Account and the OBJECTABC records only once from the database using SOQL to reduce the number of SOQL calls. I would also like to only call UPDATE once for each of these objects.
Would the best practice be to have one handler class for Case, with methods for "SetLastUpdated" and "IncreaseCaseCount"? Would I then have collections for Account and OBJECTABC that I ensure are only loaded on the first trigger call, and then subsequent calls affect the collections instead of retrieving the data again? Issues I see with this is that it could become a very, very large messy handler class.
Would the best practice be to have separate handler classes for Account and OBJECTABC, each with their own methods for "SetLastUpdated" and "IncreaseCaseCount"? This would then mean duplicating the logic for each object (e.g. I'd need to check the case type for each of these in my example, but the logic that would need to be duplicated could be much more complex).
Would the best practice be to have separate handler classes for "SetLastUpdated" and "IncreaseCaseCount"? I could then keep the logic contained, but then how would I handle loading the Account and OBJECTABC only once, and how would I pass this around from handler to handler so that I only retrieve and update the objects once?
Apologies for the long question, and I look forward to your assistance :)