Download as pdf or txt
Download as pdf or txt
You are on page 1of 59

Apex terms and keywords

1.Let's start with a simple Apex class that utilizes SOQL queries, normal Apex syntax,
and SObjects.

public class AccountProcessor {


// Method to retrieve a list of accounts with a specific industry
public static List<Account> getAccountsByIndustry(String industry) {
return [SELECT Id, Name, Industry FROM Account WHERE Industry =
:industry];
}
}

Explanation:

• This Apex class AccountProcessor contains a method getAccountsByIndustry


which accepts an industry as input and returns a list of accounts belonging to
that industry.
• It uses SOQL (Salesforce Object Query Language) to query the Salesforce
database for accounts based on the specified industry.
• The returned data is in the form of a list of Account SObjects.

Reason to use:

• This class can be used to encapsulate business logic related to retrieving


accounts by industry, promoting code reusability and maintainability.
• SOQL queries are essential for retrieving data from the Salesforce database,
and encapsulating them in methods like this improves code readability and
maintainability.

• Salesforce database for accounts based on the specified industry.


• The returned data is in the form of a list of Account SObjects.
• SOQL queries are essential for retrieving data from the Salesforce
database, and encapsulating them in methods like this improves code
readability and maintainability.
Now, let's move on to an Apex trigger that utilizes trigger context variables
and operates on related objects.

trigger OpportunityTrigger on Opportunity (before insert, before update) {


public static void updateRelatedAccounts(List<Opportunity> newOpportunities) {
Set<Id> accountIds = new Set<Id>();
for (Opportunity opp : newOpportunities) {
accountIds.add(opp.AccountId);
}
List<Account> relatedAccounts = [SELECT Id, Name FROM Account WHERE Id
IN :accountIds];
// Perform some logic on related accounts
}

if (Trigger.isBefore) {
if (Trigger.isInsert || Trigger.isUpdate) {
updateRelatedAccounts(Trigger.new);
}
}
}

Explanation:

• This is a trigger named OpportunityTrigger that operates before


inserting or updating Opportunity records.
• It contains a method updateRelatedAccounts which accepts a list of new
Opportunities and retrieves related Accounts using SOQL.
• The trigger context variables Trigger.new and Trigger.isBefore are
utilized to execute logic before the records are inserted or updated.

Reason to use:

• Triggers are commonly used to enforce complex business rules and


logic when records are inserted, updated, or deleted in Salesforce.
• Trigger context variables (Trigger.new, Trigger.old, Trigger.isBefore,
etc.) provide context about the trigger execution, allowing developers
to write logic accordingly.
• Apex Class with Constructor, Methods, Variables,
and Collections:

public class ShoppingCart {


private Map<String, Decimal> itemPrices;

public ShoppingCart() {
itemPrices = new Map<String, Decimal>();
}

public void addItem(String itemName, Decimal price) {


itemPrices.put(itemName, price);
}

public Decimal getTotalPrice() {


Decimal totalPrice = 0;
for (Decimal price : itemPrices.values()) {
totalPrice += price;
}
return totalPrice;
}

public List<String> getItemNames() {


return new List<String>(itemPrices.keySet());
}
}

Explanation:

• This Apex class ShoppingCart represents a simple shopping cart


system.
• It contains a constructor (ShoppingCart) to initialize the itemPrices
map.
• Methods like addItem, getTotalPrice, and getItemNames demonstrate
adding items to the cart, calculating the total price, and retrieving
item names respectively.
• The class utilizes a map (itemPrices) to store item names as keys and
their corresponding prices as values.
Reason to use:

• This class encapsulates shopping cart functionality, making it reusable


across different parts of an application.
• It demonstrates the usage of constructors, methods, variables, and
collections (specifically, a map) in Apex.

Apex Class with Future Method and Callout:

public class ExternalDataService {

@future(callout=true)

public static void fetchDataFromExternalSystem() {

// Perform HTTP callout to fetch data from external system

// Example: HTTP callout to fetch weather data

HttpRequest request = new HttpRequest();

request.setEndpoint('https://api.weather.com/data');

request.setMethod('GET');

HttpResponse response = new Http().send(request);

// Process the response

Explanation:

• This Apex class ExternalDataService contains a


fetchDataFromExternalSystem method decorated with
@future(callout=true).
• The method is annotated with @future, indicating that it executes
asynchronously and can make callouts to external systems.
• It demonstrates making an HTTP callout to fetch data from an
external API (in this case, weather data).

Reason to use:

• Future methods are useful for performing long-running operations


asynchronously, without blocking the main thread.
• They are commonly used for making callouts to external systems,
integrating with external APIs, or performing batch processing tasks.

Batch Apex Class:

public class AccountUpdateBatch implements Database.Batchable<sObject> {

public Database.QueryLocator start(Database.BatchableContext context) {


return Database.getQueryLocator('SELECT Id, Name, Industry FROM
Account WHERE Industry = \'Technology\'');
}

public void execute(Database.BatchableContext context, List<Account>


scope) {
for (Account acc : scope) {
// Perform some updates or business logic
acc.Description = 'Updated by batch process';
}
update scope;
}

public void finish(Database.BatchableContext context) {


// Perform any post-processing tasks
}
}

Explanation:

• This is a Batch Apex class named AccountUpdateBatch that implements


the Database.Batchable interface.
• It contains three methods: start, execute, and finish, which define the
batch job lifecycle.
• The start method returns a query locator to select accounts with a
specific industry (in this case, Technology).
• In the execute method, business logic is applied to each batch of
records (in this case, updating the account descriptions).
• The finish method allows for any post-processing tasks after batch
execution.

Reason to use:

• Batch Apex is used for processing large data sets in smaller,


manageable chunks, reducing the risk of hitting governor limits.
• It's commonly used for tasks like data cleansing, updating records, or
complex calculations on a large number of records.

Apex Test Class:


@isTest
public class AccountProcessorTest {
@isTest
static void testGetAccountsByIndustry() {
List<Account> testAccounts = new List<Account>();
testAccounts.add(new Account(Name='Test Account 1',
Industry='Technology'));
testAccounts.add(new Account(Name='Test Account 2',
Industry='Healthcare'));
insert testAccounts;

List<Account> result =
AccountProcessor.getAccountsByIndustry('Technology');
System.assertEquals(1, result.size());
System.assertEquals('Test Account 1', result[0].Name);
}
}

Explanation:

• This is an Apex test class AccountProcessorTest used to test the


getAccountsByIndustry method of the AccountProcessor class.
• It contains a test method testGetAccountsByIndustry annotated with
@isTest.
• Inside the test method, test data is created, including inserting test
accounts with different industries.
• Assertions are used to verify that the method returns the expected
results.
Reason to use:

• 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.

Apex Trigger with Trigger Context Variables and Logic:

trigger CaseTrigger on Case (before insert, after update) {

if (Trigger.isBefore && Trigger.isInsert) {

CaseHandler.handleBeforeInsert(Trigger.new);

} else if (Trigger.isAfter && Trigger.isUpdate) {

CaseHandler.handleAfterUpdate(Trigger.new, Trigger.oldMap);

public class CaseHandler {

public static void handleBeforeInsert(List<Case> newCases) {

// Perform logic before Case insertion

public static void handleAfterUpdate(List<Case> newCases, Map<Id,


Case> oldCaseMap) {

// Perform logic after Case update


}

Explanation:

• This is an Apex trigger named CaseTrigger on the Case object, which


operates before insertion and after update.
• Depending on the trigger context variables (Trigger.isBefore,
Trigger.isInsert, Trigger.isAfter, etc.), it calls appropriate methods in
the CaseHandler class.
• CaseHandler class contains static methods handleBeforeInsert and
handleAfterUpdate to handle logic before insertion and after update
respectively.

Reason to use:

• Apex triggers with trigger context variables allow developers to


execute specific logic at different points in the record lifecycle.
• Separating trigger logic into handler classes improves code
organization, readability, and maintainability.

Apex Class with Custom Metadata Type Query:


public class CustomMetadataHandler {
public static void processMetadata() {
List<MyCustomMetadata__mdt> metadataList = [SELECT Id, Label__c,
Value__c FROM MyCustomMetadata__mdt];
for (MyCustomMetadata__mdt metadata : metadataList) {
// Process metadata
}
}
}

Explanation:

• This Apex class CustomMetadataHandler queries custom metadata type


MyCustomMetadata__mdt to retrieve metadata records.
• It then processes each metadata record according to the business
logic.
Reason to use:

• Custom metadata types provide a way to create custom settings in


Salesforce that are customizable, deployable, and upgradeable.
• Querying custom metadata in Apex allows developers to dynamically
configure application behavior without hardcoding values.

Apex Class with Invocable Method for Process


Builder/Flow:
public class AccountProcessor {

@InvocableMethod(label='Update Account Status')

public static void updateAccountStatus(List<Id> accountIds, String


newStatus) {

List<Account> accountsToUpdate = [SELECT Id, Status__c FROM


Account WHERE Id IN :accountIds];

for (Account acc : accountsToUpdate) {

acc.Status__c = newStatus;

update accountsToUpdate;

Explanation:

• This Apex class AccountProcessor contains an invocable method


updateAccountStatus decorated with @InvocableMethod.
• The method accepts a list of Account Ids and a new status as
parameters.
• It queries for accounts based on the provided Ids, updates their
status, and performs the update operation.
Reason to use:

• Invocable methods allow for integration with Process Builder or Flow


in Salesforce.
• They provide a way to execute Apex code from declarative tools,
enabling complex automation and customization.

Apex Class with Schema Describe Method:


public class SchemaDescribeHandler {
public static void getFieldDetails(String objectName, String fieldName) {
Schema.SObjectType objectType =
Schema.getGlobalDescribe().get(objectName);
if (objectType != null) {
Schema.DescribeSObjectResult objectDescribe =
objectType.getDescribe();
Map<String, Schema.SObjectField> fieldMap =
objectDescribe.fields.getMap();
if (fieldMap.containsKey(fieldName)) {
Schema.DescribeFieldResult fieldDescribe =
fieldMap.get(fieldName).getDescribe();
System.debug('Field Label: ' + fieldDescribe.getLabel());
System.debug('Field Type: ' + fieldDescribe.getType());
// More field details can be retrieved similarly
} else {
System.debug('Field does not exist on the object.');
}
} else {
System.debug('Object does not exist in the schema.');
}
}
}

Explanation:

• This Apex class SchemaDescribeHandler contains a method


getFieldDetails to retrieve details about a field on a given object.
• It uses Schema describe methods to dynamically fetch metadata
about the object and its fields.
• The method prints field label, type, and other details to the debug
logs.
Reason to use:

• Schema describe methods allow developers to access metadata


about objects and fields dynamically at runtime.
• This flexibility is useful for building generic and dynamic solutions
that can adapt to changes in the schema.

s demonstrate the usage of invocable methods for process automation and


Schema describe methods for dynamic metadata access in Salesforce Apex.
Let me know if need further examples or explanations!.

Apex Class with REST Web Service:

@RestResource(urlMapping='/MyService/*')

global with sharing class MyRESTService {

@HttpGet

global static String doGet() {

// Implement GET method logic

return 'GET request processed successfully';

@HttpPost

global static String doPost(String requestBody) {

// Implement POST method logic

return 'POST request processed successfully';


}

// Additional HTTP methods can be implemented


similarly

}
Explanation:

• This is a RESTful web service implemented in Apex using the


@RestResource annotation.
• It defines HTTP methods (doGet, doPost) annotated with @HttpGet and
@HttpPost respectively.
• These methods process GET and POST requests and return responses
accordingly.

Reason to use:

• Apex REST web services provide an interface for external systems to


interact with Salesforce.
• They are used for integrating Salesforce with external applications,
allowing data exchange over HTTP.

Apex Class with Schedule Apex:


global class MyScheduledJob implements Schedulable {
global void execute(SchedulableContext context) {
// Implement scheduled job logic
System.debug('Scheduled job executed at: ' + Datetime.now());
}
}

Explanation:

• This is a scheduled Apex class MyScheduledJob implementing the


Schedulable interface.
• It contains an execute method where the scheduled job logic is
implemented.
• In this example, it simply logs a debug message indicating the
execution time.

Reason to use:

• Scheduled Apex allows developers to schedule Apex code to run at


specific times or intervals.
• It is commonly used for automating repetitive tasks like data cleanup,
report generation, or integration jobs.

s demonstrate the usage of REST web services and scheduled Apex in


Salesforce development. Let me know if need examples or further
explanations!

Apex Class with Lightning Web Components (LWC)


Controller:
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts() {
return [SELECT Id, Name, Industry FROM Account LIMIT 10];
}
}

Explanation:

• This Apex class AccountController serves as a controller for a Lightning


Web Component (LWC).
• It contains a method getAccounts annotated with
@AuraEnabled(cacheable=true), making it accessible from the client-side
Lightning component.
• The method queries for a list of accounts and returns them, allowing
the LWC to display the data.

Reason to use:

• Apex controllers for Lightning Web Components provide server-side


logic for interacting with Salesforce data.
• Annotating methods with @AuraEnabled makes them available to
Lightning components, enabling data retrieval and manipulation.
Apex Class with Email Sending:
public class EmailHandler {

public static void sendEmail(String toAddress, String subject, String


body) {

Messaging.SingleEmailMessage email = new


Messaging.SingleEmailMessage();

email.setToAddresses(new String[]{toAddress});

email.setSubject(subject);

email.setPlainTextBody(body);

Messaging.sendEmail(new
Messaging.SingleEmailMessage[]{email});

Explanation:

• This Apex class EmailHandler contains a method sendEmail to send an


email.
• It creates a Messaging.SingleEmailMessage object, sets the recipient
address, subject, and body.
• The Messaging.sendEmail method is used to send the email.

Reason to use:

• Apex provides capabilities to send emails programmatically, useful for


various scenarios like notifications, alerts, and communication with
users or external systems.
• This example demonstrates sending a simple plain text email, but
attachments, HTML content, and other features can also be utilized.

Apex Class with Database Rollback (Savepoint):


public class OpportunityProcessor {

public static void processOpportunities(List<Opportunity> oppsToUpdate) {


// Create a savepoint
Savepoint sp = Database.setSavepoint();

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:

• This Apex class OpportunityProcessor contains a method


processOpportunities to process a list of opportunities.
• It creates a savepoint using Database.setSavepoint() before
performing updates.
• In case of an exception during updates, it rolls back changes using
Database.rollback() to revert to the savepoint.

Reason to use:

• Savepoints and rollback mechanisms in Apex are crucial for handling


errors and maintaining data consistency.
• They ensure that if an error occurs during a transaction, changes
made so far can be reverted to a known state to prevent data
corruption.

Apex Class with Custom Exception Handling:


public class CustomExceptionExample {
public class MyCustomException extends Exception {}

public static void process() {


try {
// Some operation that may throw an exception
Integer result = 10 / 0; // This will cause a division by zero exception
} catch (Exception e) {
throw new MyCustomException('An error occurred: ' + e.getMessage());
}
}
}

Explanation:

• This Apex class CustomExceptionExample demonstrates custom


exception handling.
• It defines a custom exception class MyCustomException that extends the
standard Exception class.
• The process method attempts an operation that may throw an
exception, and if an exception occurs, it throws a custom exception
with a specific error message.

Reason to use:

• Custom exceptions allow developers to create meaningful and


specific error messages tailored to their application's needs.
• They improve code readability and help in identifying and handling
errors effectively.

s illustrate the usage of database rollback with savepoints and custom


exception handling in Salesforce Apex. Let me know if need examples or
further explanations!

Apex Class with System Assertions:


public class MathOperations {

public static Integer divide(Integer dividend, Integer divisor) {

// Ensure divisor is not zero

System.assert(divisor != 0, 'Divisor cannot be zero.');

return dividend / divisor;

}
}

Explanation:

• This Apex class MathOperations contains a method divide to perform


integer division.
• Before dividing, it uses System.assert to ensure that the divisor is not
zero.
• If the assertion fails (i.e., divisor is zero), it throws an assertion
exception with a custom error message.

Reason to use:

• System assertions are used to enforce logical conditions in code and


catch potential issues during development or testing.
• They provide a way to validate assumptions and prevent unexpected
behavior, improving code robustness.

Apex Class with Batchable Context Information:


public class MyBatchable implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext context) {
System.debug('Batch job started.');
// Implement start logic and return query locator
}

public void execute(Database.BatchableContext context, List<SObject>


scope) {
System.debug('Executing batch with scope size: ' + scope.size());
// Implement execute logic for each batch
}

public void finish(Database.BatchableContext context) {


System.debug('Batch job finished.');
// Implement finish logic
}
}

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:

• System debug statements are helpful for troubleshooting and


monitoring batch jobs during execution.
• They provide insights into the batch job's progress, scope size, and
completion status, aiding in debugging and optimization.

s demonstrate the usage of system assertions and batchable context


information in Salesforce Apex. Let me know if need examples or further
explanations!

Apex Class with Static Initialization Block:


public class StaticInitializer {

static {

System.debug('Static initialization block executed.');

// Perform static initialization tasks

Explanation:

• This Apex class StaticInitializer contains a static initialization block.


• The static block is executed when the class is loaded into memory for
the first time, before any other code in the class is executed.
• In this example, a debug statement is used to indicate the execution
of the static block.
Reason to use:

• Static initialization blocks are useful for performing one-time


initialization tasks for a class, such as loading configuration, setting
up static variables, or initializing static resources.

Apex Class with Interface Implementation:


public class Circle implements Shape {
public Decimal radius { get; set; }

public Decimal calculateArea() {


return Math.PI * radius * radius;
}
}
public interface Shape {
Decimal calculateArea();
}

Explanation:

• This Apex example demonstrates a class Circle implementing an


interface Shape.
• The Shape interface defines a method calculateArea.
• The Circle class implements the calculateArea method according to
the contract specified by the Shape interface.

Reason to use:

• Interfaces in Apex provide a way to define a contract for classes,


ensuring that implementing classes provide specific behavior.
• Interface implementation allows for polymorphic behavior, where
different classes can be treated uniformly based on the interface they
implement.

Apex Class with Custom Annotations:

public class AnnotationExample {


@MyCustomAnnotation(description='This method
performs a specific operation.')

public static void performOperation() {

// Method logic

public class MyCustomAnnotation extends


System.Annotation {

public String description;

}
Explanation:

• In this example, AnnotationExample class contains a method


performOperation annotated with a custom annotation
MyCustomAnnotation.
• The custom annotation MyCustomAnnotation is defined as a separate
class, extending System.Annotation.
• It includes properties like description, allowing developers to provide
additional metadata.

Reason to use:

• Custom annotations in Apex allow developers to add metadata and


behavior to methods, classes, or variables.
• They provide a way to convey additional information about the code,
such as intended usage, documentation, or configuration.

Apex Class with Queueable Interface Implementation:


public class MyQueueable implements System.Queueable {

public void execute(System.QueueableContext context) {

// Execute Queueable job logic

Explanation:

• This Apex class MyQueueable implements the System.Queueable interface.


• It contains a method execute defined by the Queueable interface, which
represents the logic to be executed asynchronously.

Reason to use:

• Queueable Apex allows developers to perform long-running tasks


asynchronously, offloading them from the main transaction.
• Implementing the Queueable interface provides a standardized way to
define asynchronous job logic, making the code maintainable and
scalable.

s illustrate the usage of custom annotations and the Queueable interface in


Salesforce Apex. Let me know if need examples or further explanations!

Apex Class with JSON Serialization and Deserialization:


public class JSONHandler {

public class AccountInfo {

public String name;

public String industry;

}
public static String serializeAccount(Account acc) {

AccountInfo info = new AccountInfo();

info.name = acc.Name;

info.industry = acc.Industry;

return JSON.serialize(info);

public static Account deserializeAccount(String jsonStr) {

AccountInfo info = (AccountInfo) JSON.deserialize(jsonStr,


AccountInfo.class);

Account acc = new Account();

acc.Name = info.name;

acc.Industry = info.industry;

return acc;

Explanation:

• This Apex class JSONHandler provides methods for serializing and


deserializing Account objects to/from JSON format.
• It defines an inner class AccountInfo to represent the structure of the
JSON data.
• serializeAccount method converts an Account object to JSON string,
while deserializeAccount method converts a JSON string to an
Account object.
Reason to use:

• JSON serialization and deserialization are essential for exchanging


data between Salesforce and external systems in JSON format.
• These methods facilitate data transformation and integration tasks,
allowing seamless communication with external APIs or systems.

Apex Class with Custom Annotations and Reflection:

public class AnnotationProcessor {

@MyCustomAnnotation(description='This method
performs a specific operation.')

public static void performOperation() {

MyCustomAnnotation annotation =
AnnotationProcessor.class.getMethod('performOperatio
n').getAnnotation(MyCustomAnnotation.class);

if (annotation != null) {

System.debug('Annotation description: ' +


annotation.description);

}
Explanation:

• This Apex class AnnotationProcessor contains a method


performOperation annotated with a custom annotation
MyCustomAnnotation.
• Using reflection, it retrieves the annotation attached to the method
and accesses its properties, such as description.

Reason to use:

• Reflection in Apex allows developers to inspect and manipulate


metadata at runtime, providing dynamic behavior.
• Combined with custom annotations, reflection enables powerful and
flexible programming patterns, such as metadata-driven
development and custom behavior injection.

Apex Class with Dynamic SOQL Query:

public class DynamicQueryHandler {

public static List<Account>


executeDynamicQuery(String fieldName, String value) {

String query = 'SELECT Id, Name, Industry FROM


Account WHERE ' + fieldName + ' = :value';

return Database.query(query);

}
Explanation:

• This Apex class DynamicQueryHandler contains a method


executeDynamicQuery that accepts field name and value parameters.
• It constructs a dynamic SOQL query using the provided field name
and value.
• The Database.query method executes the dynamic SOQL query and
returns a list of Account records.

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.

Apex Class with Database Methods for DML Operations:

public class DatabaseOperations {

public static void insertAccount(Account acc) {

Database.SaveResult result = Database.insert(acc,


false);

if (!result.isSuccess()) {

for (Database.Error error : result.getErrors()) {

System.debug('Error message: ' +


error.getMessage());

}
Explanation:

• This Apex class DatabaseOperations contains a method insertAccount


for inserting an Account record using database methods.
• It uses Database.insert method to perform the insert operation with
optional parameter allOrNone set to false, allowing partial success.
• If the insert operation fails, it retrieves and logs the error messages
using Database.Error object.

Reason to use:

• Database methods provide control and error handling capabilities


compared to DML statements (insert, update, delete).
• They allow developers to handle partial successes, retrieve detailed
error messages, and perform operations in bulk, enhancing
robustness and efficiency of data manipulation operations.

Apex Class with Sharing Settings:


public with sharing class AccountSharingController {

public List<Account> getMyAccounts() {

return [SELECT Id, Name FROM Account WHERE OwnerId =


:UserInfo.getUserId()];

Explanation:

• This Apex class AccountSharingController is declared with the with


sharing keyword, enforcing sharing rules.
• The getMyAccounts method returns a list of Account records owned by
the current user.
• Due to the with sharing keyword, the query respects the
organization's sharing settings, ensuring users only see records they
have access to.

Reason to use:

• Apex classes can be declared with with sharing or without sharing


keywords to enforce or bypass sharing rules, respectively.
• Using with sharing ensures that Apex code respects the
organization's sharing settings, enhancing data security and
compliance.

Apex Class with Public Access Modifier:

public class MathUtils {

public static Integer add(Integer num1, Integer


num2) {

return num1 + num2;

}
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:

• Declaring classes or methods as public allows other parts of the


Salesforce org to invoke them, promoting code reuse and modularity.
• Public classes and methods can be called from triggers, other classes,
Visualforce pages, Lightning components, and , making them
versatile building blocks of the Salesforce application.

Apex Class with Static Variables and Methods:

public class Counter {

public static Integer count = 0;


public static void increment() {

count++;

public static Integer getCount() {

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 variables and methods provide a way to share state and


behavior across instances of a class or even across different parts of
the application.
• They are commonly used for utility classes, counters, caches, and
other scenarios where shared data or behavior is needed.
Apex Class with Final Modifier:

public class Constants {

public static final Integer MAX_ATTEMPTS = 3;

public static final String API_ENDPOINT;

static {

API_ENDPOINT = 'https://example.com/api';

}
Explanation:

• This Apex class Constants contains final variables MAX_ATTEMPTS and


API_ENDPOINT.
• Final variables are constants whose values cannot be changed once
assigned.
• In the example, MAX_ATTEMPTS is initialized with a value, while
API_ENDPOINT is initialized in a static initialization block.

Reason to use:

• Final variables ensure that the assigned values remain constant


throughout the execution of the program, preventing accidental
modifications.
• They improve code clarity by clearly indicating that a variable's value
should not change, enhancing maintainability and reducing potential
bugs.

Apex Class with Virtual and Abstract Methods:


public abstract class Shape {
public Integer numberOfSides;

public virtual String getType() {

return 'Shape';

public abstract Decimal calculateArea();

public class Triangle extends Shape {

public Decimal base;

public Decimal height;

public override String getType() {

return 'Triangle';

public override Decimal calculateArea() {

return 0.5 * base * height;

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:

• Abstract classes and methods in Apex allow developers to define


common behavior and contracts that subclasses must implement.
• Virtual methods provide default behavior that can be overridden by
subclasses, while abstract methods require concrete implementations
in subclasses, enforcing specific behavior.

Apex Class with Annotations:


public class MyClass {

@Deprecated

public static void oldMethod() {

// Deprecated method logic

@SuppressWarnings('PMD.AvoidUsingHardCodedIP')

public static void process() {

// Suppress warning for hardcoded IP

}
Explanation:

• This Apex class MyClass demonstrates the usage of annotations like


@Deprecated and @SuppressWarnings.
• The @Deprecated annotation indicates that the oldMethod is deprecated
and should not be used.
• The @SuppressWarnings annotation suppresses a specific warning, in
this case, the warning for using a hardcoded IP address.

Reason to use:

• Annotations provide metadata about the code to the compiler or


runtime environment, influencing the behavior or treatment of the
annotated elements.
• They can convey information about deprecation, suppress warnings,
define test behavior, and , improving code clarity and maintainability.

Apex Class with Enum:

public class TrafficLight {

public enum Color {

RED, YELLOW, GREEN

public static void main(String[] args) {

Color light = Color.RED;

switch (light) {

case RED:
System.debug('Stop!');

break;

case YELLOW:

System.debug('Prepare to stop.');

break;

case GREEN:

System.debug('Go!');

break;

}
Explanation:

• This Apex class TrafficLight demonstrates the usage of enums to


represent the colors of a traffic light.
• The Color enum defines three possible values: RED, YELLOW, and GREEN.
• In the main method, a switch statement is used to perform different
actions based on the current color of the traffic light.

Reason to use:

• Enums provide a way to represent a fixed set of constants in Apex.


• They improve code readability and maintainability by providing
meaningful names for values and enabling type safety.

Apex Class with Test-Visible Method:


public class DataManipulator {
@TestVisible

private static void internalMethod() {

// Internal method logic

public static void publicMethod() {

// Public method logic

internalMethod(); // Can be accessed in tests

Explanation:

• This Apex class DataManipulator contains a method internalMethod


annotated with @TestVisible.
• The internalMethod is marked as test-visible, which means it can be
accessed in test classes but not outside of the class or in production
code.
• The publicMethod calls the internalMethod, which can be verified in test
methods.

Reason to use:

• Test-visible methods allow developers to expose internal logic for


testing purposes without making it publicly accessible.
• They facilitate unit testing by enabling access to private methods and
behavior verification within test methods.
Apex Class with Batchable Interface and Stateful
Implementation:

public class MyBatchable implements


Database.Batchable<SObject>, Database.Stateful {

private Integer totalCount = 0;

public Database.QueryLocator
start(Database.BatchableContext context) {

// Start method logic

return Database.getQueryLocator([SELECT Id FROM


Account]);

public void execute(Database.BatchableContext


context, List<SObject> scope) {

// Execute method logic

totalCount += scope.size();

public void finish(Database.BatchableContext


context) {
// Finish method logic

System.debug('Total processed records: ' +


totalCount);

}
Explanation:

• This Apex class MyBatchable implements the Database.Batchable


interface and includes the Database.Stateful marker interface.
• The class maintains state across batch executions by using a private
member variable totalCount.
• The execute method increments the totalCount with the size of each
batch's scope.

Reason to use:

• Implementing the Database.Stateful interface allows preserving state


across batch executions, which is useful for maintaining cumulative
totals or tracking progress.
• Stateful batch processing is beneficial when batch jobs need to
maintain context or share data between batch iterations.

Apex Class with Custom Iterable Class:


public class MyIterable implements Iterable<Integer> {

private List<Integer> elements;

public MyIterable(List<Integer> elements) {

this.elements = elements;

}
public Iterator<Integer> iterator() {

return new MyIterator(elements);

private class MyIterator implements Iterator<Integer> {

private Integer index = 0;

private List<Integer> elements;

public MyIterator(List<Integer> elements) {

this.elements = elements;

public Boolean hasNext() {

return index < elements.size();

public Integer next() {

return elements[index++];

}
}

Explanation:

• This Apex class MyIterable implements the Iterable<Integer> interface


to make it iterable.
• It contains a nested class MyIterator that implements the
Iterator<Integer> interface to provide iteration functionality.
• The MyIterator class keeps track of the current index and provides
methods to iterate over the elements.

Reason to use:

• Custom iterable classes allow developers to define their iteration


logic for custom data structures or collections.
• They provide flexibility and customization options for iterating over
collections, enabling advanced data processing and manipulation.

Apex Class with System Log Messages:


public class LogHandler {

public static void logInfo(String message) {

System.debug('INFO: ' + message);

public static void logError(String message) {

System.debug('ERROR: ' + message);

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:

• System log messages are essential for monitoring and debugging


Apex code.
• They provide valuable information about the execution flow, variable
values, and error conditions, aiding in troubleshooting and
diagnosing issues.

Apex Class with Iterable and Aggregate Functions:


public class DataAnalyzer {

public static Integer sum(List<Integer> numbers) {

Integer total = 0;

for (Integer num : numbers) {

total += num;

return total;

public static Decimal average(List<Integer> numbers) {

if (numbers.isEmpty()) {

return 0;
}

Decimal sum = 0;

for (Integer num : numbers) {

sum += num;

return sum / numbers.size();

Explanation:

• This Apex class DataAnalyzer contains methods to perform sum and


average calculations on a list of integers.
• The sum method calculates the total sum of the numbers in the list
using an iterative approach.
• The average method calculates the average value of the numbers by
dividing the sum by the count.

Reason to use:

• Iterable and aggregate functions are fundamental for processing


collections of data in Apex.
• They enable developers to perform various computations and
analyses on collections, such as summing, averaging, finding
minimum/maximum values, etc.

Apex Class with Exception Handling and Re-Throwing:


public class ExceptionHandler {

public static void doSomething() {

try {
// Some operation that may throw an exception

Integer result = 10 / 0; // This will cause a division by zero


exception

} catch (Exception e) {

// Handle the exception or log it

System.debug('An error occurred: ' + e.getMessage());

// Re-throw the exception for higher-level handling

throw e;

Explanation:

• This Apex class ExceptionHandler contains a method doSomething that


attempts an operation that may throw an exception.
• Inside the try block, a division by zero operation is attempted, which
results in an exception.
• The catch block catches the exception, logs an error message, and
then re-throws the exception using the throw statement.

Reason to use:

• Exception handling is crucial for gracefully handling errors and


failures in Apex code.
• Re-throwing an exception allows higher-level code or callers to
handle the exception further, providing flexibility in error handling
and recovery strategies.

Apex Class with Custom Exception:


public class CustomExceptionExample {
public class MyCustomException extends Exception {}

public static void process() {

try {

// Some operation that may throw an exception

Integer result = 10 / 0; // This will cause a division by zero


exception

} catch (Exception e) {

// Throw a custom exception with a specific message

throw new MyCustomException('An error occurred: ' +


e.getMessage());

Explanation:

• This Apex class CustomExceptionExample contains a nested class


MyCustomException which extends the standard Exception class, defining
a custom exception type.
• Inside the process method, an operation is attempted that may result
in an exception.
• If an exception occurs, a custom exception MyCustomException is
thrown with a specific error message.

Reason to use:

• Custom exceptions allow developers to define application-specific


error types and provide meaningful error messages.
• They improve code clarity and maintainability by encapsulating error-
handling logic and enabling finer-grained exception handling.

Apex Class with System Assertions and Assertion


Failure:
public class AssertionHandler {

public static Integer divide(Integer dividend, Integer divisor) {

// Ensure divisor is not zero

System.assert(divisor != 0, 'Divisor cannot be zero.');

return dividend / divisor;

Explanation:

• This Apex class AssertionHandler contains a method divide to perform


integer division.
• Before performing the division, a system assertion System.assert is
used to ensure that the divisor is not zero.
• If the assertion fails (i.e., divisor is zero), an assertion exception with a
custom error message is thrown.

Reason to use:

• System assertions are used to enforce logical conditions in code and


catch potential issues during development or testing.
• They provide a way to validate assumptions and prevent unexpected
behavior, improving code robustness.

Apex Class with Database Rollback (Savepoint):


public class TransactionHandler {
public static void processTransaction(List<Account> accountsToUpdate) {
// Create a savepoint
Savepoint sp = Database.setSavepoint();

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:

• This Apex class TransactionHandler contains a method


processTransaction to process a list of accounts in a transaction.
• It creates a savepoint using Database.setSavepoint() before
performing updates on accounts.
• If an exception occurs during the transaction, changes made so far
are rolled back using Database.rollback.

Reason to use:

• Savepoints and rollback mechanisms in Apex are crucial for handling


errors and maintaining data consistency.
• They ensure that if an error occurs during a transaction, changes
made so far can be reverted to a known state to prevent data
corruption.

Apex Class with Future Method for Asynchronous


Execution:

public class FutureHandler {

@Future

public static void processAsync(List<Account> accountsToUpdate) {

// Perform some asynchronous processing on accounts


// This method will execute asynchronously in a separate thread

update accountsToUpdate;

Explanation:

• This Apex class FutureHandler contains a future method processAsync


annotated with @Future.
• The @Future annotation indicates that the method should execute
asynchronously in a separate thread.
• Inside the method, some processing is performed on a list of
accounts, such as updates.

Reason to use:

• Future methods in Apex allow developers to offload long-running or


resource-intensive tasks from the main transaction to improve
performance and responsiveness.
• They are particularly useful for tasks that involve external callouts,
data processing, or integration tasks that don't need to block the
main transaction.

Apex Class with Queueable Interface Implementation:

public class MyQueueable implements System.Queueable {

public void execute(System.QueueableContext context) {

// Perform some queueable processing

// This method will execute asynchronously in a separate


transaction

}
}

Explanation:

• This Apex class MyQueueable implements the System.Queueable interface.


• It contains a method execute defined by the Queueable interface,
representing the logic to be executed asynchronously.
• Any logic inside the execute method will run asynchronously in a
separate transaction.

Reason to use:

• Queueable Apex allows developers to perform long-running tasks


asynchronously, offloading them from the main transaction.
• It provides flexibility and control compared to future methods,
allowing for chaining of jobs, scheduling, and monitoring of job
execution.

Apex Class with Scheduling using Schedulable Interface:

public class MyScheduledJob implements System.Schedulable {

public void execute(System.SchedulableContext context) {

// Perform scheduled job logic

// This method will execute according to the scheduled job


configuration

Explanation:

• This Apex class MyScheduledJob implements the System.Schedulable


interface.
• It contains a method execute defined by the Schedulable interface,
representing the logic to be executed when the job runs.
• The logic inside the execute method will be executed according to the
scheduled job configuration.

Reason to use:

• Schedulable Apex allows developers to schedule jobs to run at


specific times or intervals, such as nightly data processing tasks or
periodic maintenance jobs.
• It provides a way to automate routine tasks and streamline business
processes within Salesforce.

Apex Class with Custom Metadata Type Query:


public class CustomMetadataHandler {

public static void processMetadata() {

List<MyCustomMetadata__mdt> metadataRecords = [SELECT Id,


Label, Value__c FROM MyCustomMetadata__mdt];

// Process the queried custom metadata records

Explanation:

• This Apex class CustomMetadataHandler contains a method


processMetadata to query custom metadata records.
• It performs a SOQL query to retrieve records from a custom metadata
type named MyCustomMetadata__mdt.
• The queried metadata records can then be processed or used within
the Apex logic.

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.

Apex Class with Email Sending:


public class EmailSender {

public static void sendEmail(String recipientEmail, String subject,


String body) {

Messaging.SingleEmailMessage email = new


Messaging.SingleEmailMessage();

email.setToAddresses(new List<String>{recipientEmail});

email.setSubject(subject);

email.setPlainTextBody(body);

Messaging.sendEmail(new
List<Messaging.SingleEmailMessage>{email});

Explanation:

• This Apex class EmailSender contains a method sendEmail to send an


email.
• It creates a Messaging.SingleEmailMessage instance, sets the recipient
email address, subject, and body of the email.
• The Messaging.sendEmail method sends the email using Salesforce's
email delivery service.

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.

Apex Class with JSON Parsing:


public class JSONParser {

public class ContactInfo {

public String firstName;

public String lastName;

public String email;

public static ContactInfo parseContact(String jsonStr) {

ContactInfo contact = (ContactInfo)JSON.deserialize(jsonStr,


ContactInfo.class);

return contact;

Explanation:

• This Apex class JSONParser contains a nested class ContactInfo to


represent contact information.
• It includes a method parseContact to deserialize JSON data
representing contact information into an instance of ContactInfo class.
• JSON deserialization is performed using JSON.deserialize method.
Reason to use:

• JSON parsing in Apex allows developers to consume JSON data from


external systems or RESTful web services and convert it into Apex
objects.
• It enables integration with external systems that exchange data in
JSON format, facilitating seamless communication and data
exchange.

Apex Class with Remote Action for Lightning


Components:
public class RemoteActionController {

@AuraEnabled

public static String greetUser(String userName) {

return 'Hello, ' + userName + '!';

Explanation:

• This Apex class RemoteActionController contains a remote action


method greetUser annotated with @AuraEnabled.
• The greetUser method accepts a user name as a parameter and
returns a greeting message.
• Remote actions marked with @AuraEnabled can be invoked from
Lightning components to interact with the server-side logic
asynchronously.

Reason to use:

• Remote actions allow Lightning components to interact with server-


side Apex methods without requiring a full-page refresh.
• They facilitate building dynamic and responsive user interfaces in
Salesforce Lightning Experience and Communities.
Apex Class with REST API Endpoint:
@RestResource(urlMapping='/customEndpoint/*')

global with sharing class CustomRestEndpoint {

@HttpGet

global static String doGet() {

// Handle HTTP GET request logic

return 'GET request received';

@HttpPost

global static String doPost(String requestBody) {

// Handle HTTP POST request logic

return 'POST request received with body: ' + requestBody;

Explanation:

• This Apex class CustomRestEndpoint exposes a REST API endpoint using


the @RestResource annotation.
• It defines HTTP methods (doGet and doPost) annotated with @HttpGet
and @HttpPost, respectively, to handle GET and POST requests.
• The methods contain logic to process the incoming requests and
return appropriate responses.
Reason to use:

• REST API endpoints in Apex allow external systems or clients to


interact with Salesforce data and services over HTTP.
• They enable building integrations with external systems, mobile apps,
and third-party services using RESTful principles.

Apex Class with Schema Describe Methods:


public class SchemaDescribeExample {

public static void describeAccount() {

Schema.DescribeSObjectResult describeResult =
Account.SObjectType.getDescribe();

String objectName = describeResult.getName();

Map<String, Schema.SObjectField> fieldMap =


describeResult.fields.getMap();

System.debug('Object Name: ' + objectName);

System.debug('Fields:');

for (String fieldName : fieldMap.keySet()) {

Schema.SObjectField field = fieldMap.get(fieldName);

System.debug('Field Name: ' + field.getDescribe().getName());

System.debug('Field Type: ' + field.getDescribe().getType());

System.debug('Field Label: ' + field.getDescribe().getLabel());

System.debug('Is Field Updateable: ' +


field.getDescribe().isUpdateable());
System.debug('Is Field Createable: ' +
field.getDescribe().isCreateable());

Explanation:

• This Apex class SchemaDescribeExample contains a method


describeAccount to describe the Account object schema.
• It uses schema describe methods to retrieve metadata information
about the Account object and its fields.
• The method prints details such as object name, field names, types,
labels, and update/create permissions to the debug log.

Reason to use:

• Schema describe methods provide a dynamic way to access metadata


information about Salesforce objects and fields at runtime.
• They are useful for building generic or dynamic functionality, such as
generating dynamic forms, field validations, or dynamic queries
based on object metadata.

Apex Class with Custom Metadata Type Query via SOQL:


public class CustomMetadataQuery {

public static void queryMetadataRecords() {

List<MyCustomMetadata__mdt> metadataRecords = [SELECT Id,


Label, Value__c FROM MyCustomMetadata__mdt];

// Process the queried custom metadata records

}
Explanation:

• This Apex class CustomMetadataQuery contains a method


queryMetadataRecords to query custom metadata records using SOQL.
• It performs a SOQL query to retrieve records from a custom metadata
type named MyCustomMetadata__mdt.
• The queried metadata records can then be processed or used within
the Apex logic.

Reason to use:

• Querying custom metadata records via SOQL allows developers to


fetch metadata configurations stored in custom metadata types.
• It enables dynamic configuration of application behavior or settings
based on metadata records, providing greater flexibility and ease of
maintenance.

Apex Class with Named Credentials for Callouts:

public class CalloutHandler {

public static void makeCallout() {

HttpRequest request = new HttpRequest();

request.setEndpoint('callout:My_Named_Credential/some_endpoint');

request.setMethod('GET');

Http http = new Http();

HttpResponse response = http.send(request);

// Process the HTTP response


System.debug('Response status: ' + response.getStatus());

System.debug('Response body: ' + response.getBody());

Explanation:

• This Apex class CalloutHandler contains a method makeCallout to


perform an HTTP callout.
• It utilizes a named credential (My_Named_Credential) to specify the
endpoint URL securely.
• The Http class is used to send an HTTP request, and the response is
processed to retrieve status and body.

Reason to use:

• Named credentials provide a secure and centralized way to manage


authentication credentials for external services and APIs.
• They abstract endpoint URLs and authentication details from the
code, enhancing security and manageability of callouts.

Apex Class with Queueable Apex for Chainable Jobs:


public class QueueableHandler implements System.Queueable {

public void execute(System.QueueableContext context) {

// Perform queueable job logic

// Chain another queueable job

System.enqueueJob(new AnotherQueueableJob());

}
Explanation:

• This Apex class QueueableHandler implements the System.Queueable


interface to define a queueable job.
• In the execute method, it performs the main logic of the queueable
job.
• It also enqueues another queueable job (AnotherQueueableJob) to be
executed after the current job completes.

Reason to use:

• Queueable Apex allows chaining of asynchronous jobs, enabling


sequential execution of tasks in a scalable manner.
• Chaining queueable jobs facilitates complex processing workflows
and ensures orderly execution of tasks with dependencies.

Apex Class with DML Operations and Database


Savepoint:
public class DmlOperations {

public static void performDmlOperations() {

Account acc = new Account(Name = 'Test Account');

Savepoint sp = Database.setSavepoint();

try {

// Insert Account record

insert acc;

// Update the Account record

acc.Name = 'Updated Account';


update acc;

} catch (Exception e) {

// Rollback changes if an exception occurs

Database.rollback(sp);

System.debug('Rollback executed due to exception: ' +


e.getMessage());

Explanation:

• This Apex class DmlOperations contains a method performDmlOperations


to demonstrate DML operations with a database savepoint.
• It creates an Account record and sets a savepoint before performing
DML operations.
• Inside a try-catch block, it inserts the Account record and updates it,
and rolls back changes if an exception occurs during the process.

Reason to use:

• DML operations (insert, update, delete) are used to manipulate


Salesforce records in the database.
• Database savepoints allow developers to create a point in time to
which they can roll back if an exception occurs during transaction
processing, ensuring data integrity.

Apex Class with System.assert Statements for Unit


Testing:
public class MathOperations {

public static Integer divide(Integer dividend, Integer divisor) {


System.assert(divisor != 0, 'Divisor cannot be zero.');

return dividend / divisor;

Explanation:

• This Apex class MathOperations contains a method divide to perform


integer division.
• It includes a System.assert statement to ensure that the divisor is not
zero before performing division.
• If the assertion fails (i.e., divisor is zero), an assertion exception with a
custom error message is thrown.

Reason to use:

• System.assert statements are used in unit tests to verify expected


conditions or behaviors in the code under test.
• They help ensure that code behaves as expected and catch potential
issues or regressions during development or changes.

Set.size(): Method used to return the number of elements in a set in Apex.


Map Class: Provides methods for working with maps in Apex. Map.put():
Method used to add key-value pairs to a map in Apex. Map.get(): Method
used to retrieve the value associated with a key in a map in Apex.
Map.containsKey(): Method used to check if a map contains a specific key
in Apex. Map.containsValue():
Map.containsValue():

In Apex, the Map.containsValue() method is used to check if a map contains


a specific value. This method returns a Boolean value (true or false)
indicating whether the map contains the specified value or not.

Here's how can use Map.containsValue():

Map<String, Integer> myMap = new Map<String, Integer>();


myMap.put('A', 1);

myMap.put('B', 2);

myMap.put('C', 3);

Boolean containsValue = myMap.containsValue(2); // Check if the map


contains the value 2

System.debug('Contains value 2: ' + containsValue); // Output: true

containsValue = myMap.containsValue(4); // Check if the map


contains the value 4

System.debug('Contains value 4: ' + containsValue); // Output: false

Explanation:

• In this example, a map myMap is created with key-value pairs.


• The containsValue() method is then used to check if the map contains
specific values (2 and 4).
• The method returns true for the value 2, indicating that it exists in the
map, and false for the value 4, indicating that it doesn't exist in the
map.

Usage:

• Map.containsValue() is useful when need to determine if a map


contains a specific value without needing to know its corresponding
key.
• It can be used to perform conditional logic or validation based on the
presence of values within a map in Apex.

You might also like