Professional Documents
Culture Documents
Salesforce Apex Magic - Real-World Business Scenarios! ?
Salesforce Apex Magic - Real-World Business Scenarios! ?
1.Let's start with a simple Apex class that utilizes SOQL queries, normal Apex syntax,
and SObjects.
Explanation:
Reason to use:
if (Trigger.isBefore) {
if (Trigger.isInsert || Trigger.isUpdate) {
updateRelatedAccounts(Trigger.new);
}
}
}
Explanation:
Reason to use:
public ShoppingCart() {
itemPrices = new Map<String, Decimal>();
}
Explanation:
@future(callout=true)
request.setEndpoint('https://api.weather.com/data');
request.setMethod('GET');
Explanation:
Reason to use:
Explanation:
Reason to use:
List<Account> result =
AccountProcessor.getAccountsByIndustry('Technology');
System.assertEquals(1, result.size());
System.assertEquals('Test Account 1', result[0].Name);
}
}
Explanation:
• Apex test classes are crucial for ensuring the reliability and
functionality of Apex code.
• They validate the behavior of Apex classes and methods under
different scenarios, helping to catch bugs and errors early in the
development process.
CaseHandler.handleBeforeInsert(Trigger.new);
CaseHandler.handleAfterUpdate(Trigger.new, Trigger.oldMap);
Explanation:
Reason to use:
Explanation:
acc.Status__c = newStatus;
update accountsToUpdate;
Explanation:
Explanation:
@RestResource(urlMapping='/MyService/*')
@HttpGet
@HttpPost
}
Explanation:
Reason to use:
Explanation:
Reason to use:
Explanation:
Reason to use:
email.setToAddresses(new String[]{toAddress});
email.setSubject(subject);
email.setPlainTextBody(body);
Messaging.sendEmail(new
Messaging.SingleEmailMessage[]{email});
Explanation:
Reason to use:
try {
// Perform some updates on opportunities
update oppsToUpdate;
} catch (Exception e) {
// Rollback changes if an exception occurs
Database.rollback(sp);
System.debug('Rollback executed due to exception: ' + e.getMessage());
}
}
}
Explanation:
Reason to use:
Explanation:
Reason to use:
}
}
Explanation:
Reason to use:
Explanation:
• This is a Batch Apex class MyBatchable implementing the
Database.Batchable interface.
• It contains methods start, execute, and finish to define the batch job
lifecycle.
• System debug statements are used to log information at different
stages of batch execution.
Reason to use:
static {
Explanation:
Explanation:
Reason to use:
// Method logic
}
Explanation:
Reason to use:
Explanation:
Reason to use:
}
public static String serializeAccount(Account acc) {
info.name = acc.Name;
info.industry = acc.Industry;
return JSON.serialize(info);
acc.Name = info.name;
acc.Industry = info.industry;
return acc;
Explanation:
@MyCustomAnnotation(description='This method
performs a specific operation.')
MyCustomAnnotation annotation =
AnnotationProcessor.class.getMethod('performOperatio
n').getAnnotation(MyCustomAnnotation.class);
if (annotation != null) {
}
Explanation:
Reason to use:
return Database.query(query);
}
Explanation:
Reason to use:
• Dynamic SOQL queries allow developers to build queries dynamically
at runtime, based on user input or changing requirements.
• They provide flexibility in querying records and can be useful in
scenarios where the query criteria are not known at compile-time.
if (!result.isSuccess()) {
}
Explanation:
Reason to use:
Explanation:
Reason to use:
}
Explanation:
• This Apex class MathUtils is declared with the public access modifier,
making it accessible from other classes and triggers within the
Salesforce org.
• The add method performs addition of two integers and returns the
result.
Reason to use:
count++;
return count;
Explanation:
• This Apex class Counter contains a static variable count to track the
number of increments.
• It also includes static methods increment to increase the count and
getCount to retrieve the current count.
• Static variables and methods belong to the class itself rather than to
instances of the class, allowing shared access across multiple
instances and contexts.
Reason to use:
static {
API_ENDPOINT = 'https://example.com/api';
}
Explanation:
Reason to use:
return 'Shape';
return 'Triangle';
Explanation:
• This Apex example defines an abstract class Shape representing a
geometric shape.
• The Shape class contains a virtual method getType and an abstract
method calculateArea.
• The Triangle class extends Shape and provides concrete
implementations for getType and calculateArea methods.
Reason to use:
@Deprecated
@SuppressWarnings('PMD.AvoidUsingHardCodedIP')
}
Explanation:
Reason to use:
switch (light) {
case RED:
System.debug('Stop!');
break;
case YELLOW:
System.debug('Prepare to stop.');
break;
case GREEN:
System.debug('Go!');
break;
}
Explanation:
Reason to use:
Explanation:
Reason to use:
public Database.QueryLocator
start(Database.BatchableContext context) {
totalCount += scope.size();
}
Explanation:
Reason to use:
this.elements = elements;
}
public Iterator<Integer> iterator() {
this.elements = elements;
return elements[index++];
}
}
Explanation:
Reason to use:
Explanation:
• This Apex class LogHandler contains methods to log informational and
error messages.
• The logInfo method prefixes the message with "INFO:" and logs it
using System.debug.
• Similarly, the logError method prefixes the message with "ERROR:"
before logging.
Reason to use:
Integer total = 0;
total += num;
return total;
if (numbers.isEmpty()) {
return 0;
}
Decimal sum = 0;
sum += num;
Explanation:
Reason to use:
try {
// Some operation that may throw an exception
} catch (Exception e) {
throw e;
Explanation:
Reason to use:
try {
} catch (Exception e) {
Explanation:
Reason to use:
Explanation:
Reason to use:
try {
// Perform some updates on accounts
update accountsToUpdate;
} catch (Exception e) {
// Rollback changes if an exception occurs
Database.rollback(sp);
System.debug('Rollback executed due to exception: ' +
e.getMessage());
}
}
}
Explanation:
Reason to use:
@Future
update accountsToUpdate;
Explanation:
Reason to use:
}
}
Explanation:
Reason to use:
Explanation:
Reason to use:
Explanation:
Reason to use:
• Custom metadata types provide a way to configure application
settings, data mappings, or business rules in a customizable and
scalable manner.
• Querying custom metadata records in Apex allows developers to
dynamically access and utilize metadata configurations within their
code.
email.setToAddresses(new List<String>{recipientEmail});
email.setSubject(subject);
email.setPlainTextBody(body);
Messaging.sendEmail(new
List<Messaging.SingleEmailMessage>{email});
Explanation:
Reason to use:
• Apex provides capabilities to send emails programmatically, enabling
automation of email notifications, alerts, or communication
processes.
• Email sending functionality is useful for various scenarios such as
notifying users, sending reports, or integrating with external systems
via email.
return contact;
Explanation:
@AuraEnabled
Explanation:
Reason to use:
@HttpGet
@HttpPost
Explanation:
Schema.DescribeSObjectResult describeResult =
Account.SObjectType.getDescribe();
System.debug('Fields:');
Explanation:
Reason to use:
}
Explanation:
Reason to use:
request.setEndpoint('callout:My_Named_Credential/some_endpoint');
request.setMethod('GET');
Explanation:
Reason to use:
System.enqueueJob(new AnotherQueueableJob());
}
Explanation:
Reason to use:
Savepoint sp = Database.setSavepoint();
try {
insert acc;
} catch (Exception e) {
Database.rollback(sp);
Explanation:
Reason to use:
Explanation:
Reason to use:
myMap.put('B', 2);
myMap.put('C', 3);
Explanation:
Usage: