Theoretical knowledge meets real-world constraints. Every scenario below is based on actual challenges faced during Salesforce development and data migration.
Scenario: You are importing 200 Contacts. Due to a validation rule, 5 Contacts will fail. The requirement is to save the other 195 valid records without failing the entire transaction.
"How do you handle this to allow partial processing and log the specific errors?"
// The Solution: Database Methods
Database.SaveResult[] srList = Database.insert(conList, false);
// Audit the results
for(Database.SaveResult sr : srList) {
if (!sr.isSuccess()) {
// Log failure details
System.debug(sr.getErrors()[0].getMessage());
}
}
Scenario: You are creating a Task and trying to link it to an Account using the WhoId field. The code crashes. Why?
"Field Integrity Exception: id value of incorrect type"
// The Diagnosis
WhoId = Account.Id; // ERROR!
// The Fix
myTask.WhatId = acc.Id; // Links to Objects
myTask.WhoId = con.Id; // Links to People
Scenario: You need to write a method that accepts a first name, last name, and email to create a new Contact record.
// The Implementation
public class UseCase_1 {
public static void createContactRecord(String fName, String lName, String email) {
List<Contact> conList = new List<Contact>();
Contact con = new Contact();
if (!String.isBlank(lName)) {
con.FirstName = fName;
con.LastName = lName;
con.Email = email;
conList.add(con);
}
if (conList.size() > 0) {
Database.insert(conList, false); // Partial success
}
}
}
Scenario: You need to build a reusable method that calculates Simple Interest based on Principal, Rate of Interest, and Time (in years).
NullPointerException.
0 if any input is
missing.
// The Implementation
public class UseCase_2 {
// Returns SI = (P * R * T) / 100
public static Decimal calculateIntrest(Decimal p, Decimal r, Integer t) {
if (p != null && r != null && t != null) {
Decimal si = (p * r * t) / 100;
return si;
}
return 0;
}
}
Scenario: You need to create a service method that accepts a single email address and sends a high-priority notification email directly from Salesforce.
// The Implementation
public with sharing class UseCase_3 {
public static void sendEmail(String email) {
List<String> emailList = new List<String>{email};
// Initialize Message
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setSubject('URGENT- Take a Look');
mail.setPlainTextBody('This is a notification triggered via Apex for you');
mail.setToAddresses(emailList);
// Send the List
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
}
}