All About Future methods

What are future methods ?

Ans : 
1. Methods used when you want to run apex transaction asynchronously
2. Static methods with @future annotation and void return type
3. Accepts only primitive types as arguments
4. Only 50 future calls are allowed per apex invocation
5. You can not call one future method from another future method

When we generally use future methods?
Ans:
1. When you want to make callouts to external web service in trigger
2. When you want to make callout after DML operation
3. When process needs to run in their own thread for processing records or complex calculaions
4. Isolating DML operations on different SObjects types to prevent mixed DML error . When we try to insert set up and Non set up object at a time we come across mixed DML exception.

Why we can not pass Sobjects to future methods?
Ans:
The reason why objects can’t be passed as arguments to future methods is because the object can change between the time you call the method and the time that it actually executes. Remember, future methods are executed when system resources become available. In this case, the future method may have an old object value when it actually executes, which can cause all sorts of bad things to happen.

How to pass Sobject to future method?
Ans:
If you want to pass Sobject we have work around : 
We can serialise Sobject to Json string and can pass string future method. In future method we can deserialise string  to Sobject and perform necessary operations.

Best practices for writing future methods :
Ans: 
1. Ensure future method executes as fast as possible
2. Try to bundle more than one callouts in single future method instead of separate future methods
3. To process large no of records consider Batch apex.
4. Consider trigger enqueuing the @future calls is able to handle a trigger collection of 200 records.

Things to consider while writing test class for future methods.
Ans:
1. Test code cannot actually send callouts to external systems, so you’ll have to ‘mock’ the callout for test coverage. 
2. Enclose your test code between test.startTest() and test.StopTest()

What is System.isFuture() ?
Ans:
1. It returns true if currently executing code is invoked by code contained in method annoted with @future.

Comments

Popular posts from this blog

Salesforce interview questions and answers : All About Triggers : Part 1

Salesforce interview questions and answers : All about SOQL : Part 1