Jaganpro / Apex-Commandments

Curated Information about Apex Best Practices from Tech Sessions and Personal experience

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Apex-Commandments

Apex Best Practices

Rule 1: Don't use SOQL queries inside For-Loops

  • Queries in For Loops can break governer limits
  • Total Query limit per execution context is 100.

image

  • Take SOQL queries out of For-Loop. Here in this case, we are using relationship queries.

image

Rule 2: Don't use DML Operations inside For-Loops

  • Using DML Operations inside for loops can break governer limits.
  • DML Operation Limit per execution context is 150.

 image

  • Add the instance variable to a list and then perform DML operation outside of For-loop

 image

Rule 3: Define only 1 trigger per Object

  • This is because, if we have multiple triggers per Object, salesforce does not guarentee the order of execution.

image

Rule 4: Don't add code directly to Triggers other than reference to other classes or methods

  • As best practice, always create an Handler Classes

image

Rule 5: Use Maps for Queries whenever possible

  • By using Map, we can always retrieve a specific record using ID.

image

Rule 6: Use Relationships in SOQL to reduce Queries

  • Parent-child and Child-Parent Relationships in Salesforce are useful to reduce number of Queries, so that the risk of breaking governer limits are reduced

  • When we go from Child-Parent, we can go upto 5 levels up in the hierarchy.

  • When we go from Parent-Child, it is limited to 1 level down.

image

Rule 7: Aim for 100% Test Coverage

  • Atleast 3 scenarios should be tested:

    • Positive Test Case
    • Negative Test Case
    • User/Profile/Role based Case
  • Example of a Positive Test Case

image

  • Example of a Negative Test Case
  • We are forcing an error and we are checking the error which was thrown was the error which we are expecting.

 image

  • Example of User/Role/Profile based Test Case
  • Use System.runAs() method for this type of test cases.

image

Rule 8: Write Useful Test Cases

  • Every test needs to use assertions
    • Assert(A==B,"Reason why Assert Failed")
    • AssertEquals(A==B, "Reason why Assert Failed")
    • AssertNotEquals(A==B, "Reason why Assert Failed")

Rule 9: Test One thing at a time

  • Unit Test - Test Driven Development (TDD)

image

About

Curated Information about Apex Best Practices from Tech Sessions and Personal experience

License:MIT License