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

This article discusses on the small things that we overlook while writing code in Apex. You might have got habituated in doing the below explained items in your own usual way, but there is still a better way to achieve them. Try it!

1. Sending records to @future method:
                  We all know that future methods run in asynchronous mode, and will not accept Sobject types as parameters. Consider this scenario, where we need to send List<Account> to a future method. As we can't send the List<Account>, we usually send the record ids to future method, and then query the records in future method.
                 An alternate way to do this is we can send the the serialized list to future method. We can serialize the List<Account> using Json.serialize() method. We can deserialize the list in future method using Json.deserialize(). Below is the syntax to serialize & deserialize List<Account>:
//Serializing list of accounts.
List<Account> accountList = new List<Account>([select id from account]);
String serializedList = JSON.serialize(accountList);

//Deserializing list of accounts.
List<Account> deserializedList = (List<Account>)JSON.deserialize(serializedList, 
                                                            List<Account>.class);
2. Updating data(records):
                  To update records, we need not query the records again if you have the record ids. Instead, we can simply create an instance of the object, assign the id and update the fields. For example, I want to update a contact's lastname,
Contact c1 = new Contact(id='<Record id of contact>', lastname='lName');
update c1;
3. Commenting/Uncommenting code during Datatype changes:
                Your application is live in production environment, and you want to change the datatype of a field, say from text to textarea. As the field will be referenced at various places over the code, you have to:
  • Comment the code wherever this field is being referenced.
  • Change the data type of field.
  • Deploy the code to production.
  • Uncomment the commented code &
  • Deploy the uncommented code to production.
Instead of doing the deployment two times, we can achieve this in a single deployment:
  • Replace the field being referenced using Sobject.get() & Sobject.put() methods. For example,
  • //If a value is being set, use Sobject.put() to set the value.
    Account acc = [select id from account limit 1];
    acc.put('name','Account1');
    
    //To get the value of a field, use Sobject.get() to get the value.
    String name = acc.get('name');
    
  • Change the data type of the field.
  • Deploy the code to production.
Stay tuned! for Part 2 :)

Comments

Post a Comment

Popular posts from this blog

New Beta Architect Certifications by Salesforce

How to deploy Processes in Process builder using ANT?