Thursday, August 29, 2019

Best Practices to write Apex Code & Triggers

Best Practices to write Apex Code:

Ø  Use Aysnchronous Apex(Using @future annotation) when the logic doesn’t need to be executed synchronously.

Ø  Asysnchronous Apex should be bulkified.

Ø  Apex code must provide proper Exception handling.

Ø  Prevent SOQL & SOSL injection attack by using static queries, binding variables and EscapeSingleQuotes method.

Ø  When querying large data, SOQL For loop should be used.

Ø  Use SOSL over SOQL if the requirement matches as it’s much faster.

Ø  Use Apex Limit method to avoid hitting Governor Limit exception.

Ø  No SOQL & SOSL inside for loops.

Ø  No Asynchronous method(@future) inside loops.

Ø  Do not use hardcoded Ids.


Best Practices to write Triggers:

Ø  There should be only One Trigger for each object.

Ø  Avoid complex logic on triggers. To simplify testing and reuse, trigger should delegate to Apex Classes which contain the actual logic.

Ø  Bulkify any helper classes or methods.

Ø  Triggers should be bulkified and be able to process upto 200 records for each call.

Ø  Execute DML statements using Collections instead of individual records per DML statements.

Ø  Use Collections in SOQL Where clause to retrieve all records back in single query.

Ø  Use a consistent Naming Convention using Object Name(e.g.- AccountName).


No comments:

Post a Comment