Overview
Clayton enforces a best practice rule that prohibits embedding business logic directly within Apex triggers. Instead, logic should be delegated to a handler class or trigger framework. This approach promotes clean architecture, improves maintainability, and makes testing and reuse significantly easier.
This rule is classified as an Error because while it may not break functionality immediately, it undermines the long-term health and scalability of your Salesforce codebase.
Why This Matters
Embedding business logic in triggers can lead to:
Poor Testability: Logic tied directly to triggers is difficult to isolate and unit test.
Limited Reusability: Logic inside a trigger can’t be reused in other parts of your codebase.
Harder Maintenance: As triggers grow more complex, they become harder to read and maintain.
Deviation from Best Practices: Salesforce recommends using a trigger-handler pattern to maintain a clean separation of concerns.
Clayton flags this pattern to help teams catch and correct it before it becomes a larger problem.
What Triggers This Rule
Any Apex trigger that contains business logic within the trigger body will be flagged.
Example of a Violation
apexCopyEdittrigger AccountTrigger on Account (before insert) { for (Account acc : Trigger.new) { if (acc.AnnualRevenue > 1000000) { acc.Rating = 'Hot'; } } }
In this example, the trigger itself contains conditional logic that should be moved to a dedicated handler class.
Recommended Fix
Refactor the trigger to delegate logic to a separate handler class. This follows the trigger-handler pattern and ensures that your logic is modular, testable, and easier to manage.
Corrected Version
apexCopyEdittrigger AccountTrigger on Account (before insert) { AccountTriggerHandler.handleBeforeInsert(Trigger.new); }
apexCopyEditpublic class AccountTriggerHandler { public static void handleBeforeInsert(List<Account> newAccounts) { for (Account acc : newAccounts) { if (acc.AnnualRevenue > 1000000) { acc.Rating = 'Hot'; } } } }
Summary
Avoid placing business logic directly in triggers. Instead, use a handler class to process logic outside the trigger body. This ensures better structure, testability, and adherence to Salesforce development best practices. Clayton will flag violations as errors, helping your team maintain a clean and scalable codebase.