Small things in Apex which we can achieve in a smart way! - Part 2


Hope you guys enjoyed reading Part1. Here we go!
Below mentioned are few things which you might have missed while coding. Happy reading!!.

Mixed Save Actions on sObject Lists:
              While working in Trigger or an ApexClass, we generally prepare different lists of multiple object types and perform DML operations for each sObject list. For example, to update accounts, contacts & cases we prepare List<Account>, List<contact> & List<case>, then we update each list separately which consumes unnecessary DML operations.
               Instead, we can simply put all the three lists into a single sObject list and perform the DML only once.

               Let's get into details on how this works. In the above code snippet contactList contains 3 records say c1, c2, c3, accountList has 2 records say a1, a2 and caseList has 2 records case1,case2. Salesforce processes multiple object types in a list in Chunks. The sObjList  has 3 chunks now.
            Data is committed on a chunk-by-chunk basis. Any Apex triggers related to the records in a chunk are invoked once per chunk. Each call can process up to 10 chunks. If the sObjects array contains more than 10 chunks, you must process the records in more than one call.
Note: You have to make sure that SObjList has to be properly populated, because if you populate the SObjList in the following way:

Guess how many chunks ? The answer is not 2 chunks. It is 4 chunks:
Chunk 1 : account1, account2
Chunk 2 : contact1, contact2, contact3
Chunk 3 : account3, account4
Chunk 4 : contact4, contact5
Click here for official documentation.

Running Test classes:
               Your production environment has so many applications. You have deployed new application to production. To test the code coverage of the classes related to your application, we usually:
  • Go to Apex Test execution wizard.
  • Manually, select the test classes one by one.
  • Run tests.      
With Spring 16 Release, you can now create Test Suites.  A test suite holds a set of test classes. You can create a test suite using ApexTestSuite object. To associate a test class to this suite, create a TestSuiteMembership object.

Assigning RecordType :
           Most of the developers might follow the below approaches for assigning a record type to a record:
  • Query the record type from RecordType object or
  • Use Schema getDescribe() calls.
You need not do this in all the cases. You can simply create an instance of the Recordtype and assign.

I came to know about this from this post by BigAss


Comments

  1. For grouping DML statements I'd recommend using the Unit Of Work pattern. It's built in to FinancialForce's framework.

    ReplyDelete
  2. Awesome...these are really helpful tricks. Thanks for sharing :)

    ReplyDelete

Post a Comment

Popular posts from this blog

New Beta Architect Certifications by Salesforce

How to deploy Processes in Process builder using ANT?