Defensive Apex Programming in Salesforce!!!
Logesh Matheswaran
Technical Consultant at Salesforce | Creator of Formulizer ?? | Co-Creator of ApexPulse (AppExchange) ?? | Salesforce Credentials Ambassador ?? | Salesforce Insider ?? ?? | Four Star Agentblazer ????
Defensive Apex Programming is a set of best practices and techniques for writing Apex code that is resilient to unexpected events and errors. It is a way of writing code that anticipates and handles potential problems before they cause outages or data loss.
Why do we need defensive programming?
Let's take a look at some examples of how the code behaves if it is in and not in defensive mode.
Disclaimer: The following example I have added is just for demonstration purposes only??
Example 1 : Making Future Calls
Wrong way of making Future Calls - Not Defensive ?
public void callFuture(){
futureMethod();
}
//Future Apex Class
@future
public static void futureMethod(){
//business logic goes here
}
Problems may arise with the above approach,
Defensive way of making Future Calls - Defensive ?
public void callFuture(){
if(System.isFuture() || System.isBatch())
{
regularCall();
}
else {
if(Limits.getFutureCalls() < Limits.getLimitFutureCalls()){
doFutureCall();
}
else {
// log the message to understand why future call is denied
}
}
}
//Future Apex Class
@future
public static void doFutureCall(){
regularCall();
}
public static void regularCall(){
//business logic goes here
}
With the above approach, future calls are handled properly and you get to know if it fails.
领英推荐
Example 2 : DML Operations
Improper way of handling DMLs - Not Defensive ?
Insert accList;
Problems may arise with the above approach,
A proper way of handling DMLs - Defensive ?
Database.SaveResult[] srList = Database.insert(accList, false);
for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
System.debug('Successfully inserted account ::: Account ID: ' + sr.getId());
}
else {
for(Database.Error err : sr.getErrors()) {
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('Account fields that affected this error: ' + err.getFields());
}
}
}
With the above approach, you are handling DMLs properly and errors gracefully.
Other Options: Use Try, catch, final blocks; Custom Exceptions to handle the errors properly.
Summary: Make your code more defective in order to be resilient, robust, secure, monitor themselves and withstand any kind of unexpected situations.
P.S: More Lines of Code with a defensive approach > minimal code with a defect ??
Credits & Inspired from: DAN APPLEMAN (https://www.salesforce.com/video/193789/#:~:text=Have%20you%20ever%20finished%20writing,you%20need%20to%20program%20defensively.)
Happy Trailblazing!!!