In the previous post we discussed the benefits of setting up custom settings early on in the project lifecycle to act essentially as system config values. In this post we will look at the bread and butter of a salesforce developers work; triggers.

Whilst the process builder will mean that common triggers will no longer be required, I cannot foresee a scenario where triggers will be completely extinct on the salesforce platform. The flexibility they provide is immense and whilst I certainly advocate for clicks over code, there are genuine use case for using triggers over workflows in certain situations. That is provided the developers are competent, otherwise you are better of using workflows. Even if it means you are taking a sledgehammer to the problem.

How not to implement a trigger

When asked to write a trigger, the temptation is to go into setup and find the object the trigger needs to written for and select trigger and new from the UI. Don't give in to temptation. This is a very slippery slope and as a responsible developer you should always have in the back of your mind the maintainability of what you are doing.

So how should we go about setting up a framework for writing triggers.

The right way / simple way

There are several types of implementations I have seen, all of varying degrees of complexity.

  • The very sophisticated, as seen here
  • The interface approach, as seen here
  • Or, the simpler "one trigger per object" - which we will describe below.

Whilst the first two obviously provide much more flexibility and robustness, as eluded to by Dan Appleman on his blog. It is quite feasible that your Salesforce implementation will not require such complexity. If on the other hand you are developing a AppExchange product then the simple solution described here might not be sufficient.

At the core of this approach - is that that we want to control the order of execution, if you have multiple triggers per object then there is no way to control order of execution.

Logic less triggers, mainly to aid testing effort but to also follow good object-oriented principles in the sense that you can reuse business logic. If you were to implement your logic within the trigger this would not be possible.

So for example you would define a trigger on opportunity with all the possible operation like below

trigger OpportunityTrigger on Opportunity (before insert, before update, before delete, 
                                            after insert, after update, after delete, 
                                            after undelete) {

And then also define an apex class to carry out the necessary business logic per operation

public class OpportunityTriggerHandler{
  public static void handleAfterInsert(List opps) {
    // handler logic

For a more detailed discussion on the topic check out this great Q&A on Salesforce StackExchange