Pages

Friday, December 16, 2016

Salesforce Best Practices

Apex Best Practices

  • Bulkify your code.
  • Avoid SOQL Queries or DML statements inside FOR loops.
  • Bulkify your helper methods.
  • Using collections, streamlining queries and efficient for loops.
  • Use of limit apex methods to avoid hitting governor limits. Example: Limits.getLimitQueries()
  • Avoid hardcoding of ID's.

Testing Best Practices

  • In the case of conditional logic, execute each branch of code logic.
  • Make calls to methods using both valid and invalid inputs.
  • Use system.assert methods to prove that code behaves properly.
  • Use runAs method to test your application in different user contexts. 
  • Use isTest annotation.
  • Not assume that record Id's are in sequential order.
  • Create all test data before calling the starttest method.
  • Since tests don't commit, you won't need to delete any data. 

Future Method Best Practices

  • Ensure that future methods execute as fast as possible.
  • If using web service callouts, try to bundle all callouts together from the same future method, rather than using a separate method for each callout.
  • Conduct thorough testing at scale. Test that a trigger enqueuing the @future calls is able to handle a trigger collection of 200 records. This helps determine if delays may occur given the design at current and future volumes.
  • Consider using batch apex instead of future methods to process large number of records asynchronously. This is more efficient than creating future request for each record. 

Batch Job Best Practices

  • Only use Batch Apex if you have more than one batch of records. If you don't have enough records to run more than one batch, you are probably better off using Queueable Apex.
  • Tune any SOQL query to gather the records to execute as quickly as possible.
  • Minimize the number of asynchronous requests created to minimize the chance of delays.
  • Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to guarantee that the trigger won't add more batch jobs  than the limit.  

No comments:

Post a Comment