Skip to content

RFC: Codify trigger logic on related objects #1

@YodaDaCoda

Description

@YodaDaCoda

Triggers shouldn't modify other objects - they should perform a DML operation and allow a trigger for the other object to perform the logic.

This keeps logic for any given object with that object and allows for updating that object and applying the relevant logic from anywhere.

Very contrived example (which should be using a trigger handler!):

BAD

trigger naughtyContactTrigger on Contact (after UPDATE) {
    List<Account> updateList = new List<Account>();
    for (Contact c : Trigger.new) {
        if (String.isBlank(c.AccountId)) {
            continue;
        }
        if (c.LastName == 'Testington') {
            updateList.add(new Account(Id=c.AccountId, Name='Testington Account'));
        }
    }
    UPDATE updateList;
}

GOOD

trigger goodContactTrigger on Contact (after UPDATE) {
    List<Account> updateList = new List<Account>();
    for (Contact c : Trigger.new) {
        if (String.isBlank(c.AccountId)) {
            continue;
        }
        updateList.add(new Account(Id=c.AccountId));
    }
    UPDATE updateList;
}
trigger goodAccountTrigger on Account (before UPDATE) {
    Map<Id, Account> accountMap = new Map<Id, Account>([
        SELECT
            Id,
            (SELECT Id, LastName FROM Contacts)
        FROM Account
        WHERE Id IN :Trigger.new
     ]);

    for (Account a : Trigger.new) {
        Account aa = accountMap.get(a.Id);
        for (Contact c : aa.Contacts) {
            if (c.LastName == 'Testington') {
                a.Name = 'Testington Account';
            }
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions