A. Bulkify Your Code:
Design your code to efficiently handle multiple records in a single operation, especially for triggers, which can process up to 200 records simultaneously. For example, during a data load, if your code isn’t structured to handle bulk records, it may lead to unexpected errors or inconsistencies. Bulkification ensures smooth execution even with large datasets.
What to Do
What NOT to Do
B. Avoid DML/SOQL Inside Loops:
When you need to insert, update, or query multiple records, avoid placing DML statements (like insert or update) or SOQL queries inside a loop. This practice is inefficient and can quickly breach Salesforce’s governor limits, leading to errors or performance issues. Instead, collect all the records or queries first and perform these operations outside the loop to improve efficiency and stability.
What to Do
What NOT to Do
C. Avoid Hardcoding IDs:
Hardcoding IDs directly in your Apex code makes it less flexible and harder to maintain, as these IDs might change between environments like sandbox and production. Instead, use custom settings, custom metadata, or dynamic queries to retrieve the IDs programmatically. This makes your code portable, adaptable, and less prone to errors during deployments.
What to Do
What NOT to Do
D. Avoid Nested For Loops:
Nested loops in Apex code can severely affect performance by increasing complexity and execution time, especially when handling large datasets. Instead of using nested loops, utilize collections like lists, maps, and sets to optimize your logic and ensure your code stays within Salesforce’s governor limits.
What to Do
What NOT to Do
E. Enforce Sharing Rules in Apex:
By default, Apex classes run in System Mode, bypassing field-level and object-level security. To ensure compliance with organizational security policies, use the with sharing keyword in your classes. This enforces sharing rules and ensures the code respects user permissions, protecting sensitive data from unauthorized access.
What to Do
What NOT to Do
F. Limit One Trigger per Object:
Follow the best practice of having only one trigger per object. This improves code maintainability and allows better control over the order of execution. If you have multiple triggers on the same object, it becomes challenging to predict the order in which they will execute, leading to potential conflicts or unintended behavior.
What to Do
What NOT to Do
G. Use Handler Classes for Triggers:
Always separate your trigger logic by creating a dedicated handler class. This approach improves organization, readability, and reusability of your code. It simplifies testing and debugging by isolating business logic in a handler method. Additionally, it helps scale your codebase more effectively, ensuring that changes or updates can be managed efficiently.
What to Do
What NOT to Do
For any queries please reach out to support@astreait.com