You are on page 1of 37

1. What is apex?

Apex is a programming language developed by Salesforce, it is salesforce’s proprietary programming language and can be used only on
Salesforce platform.
Apex is a strongly typed, object-oriented programming language that allows developers to execute code on Salesforce platform.
It also allows developers to write code to call API’s
Apex syntax looks like Java or C# and acts like database stored procedures;
It enables developers to add business logic to most system events, including button clicks, related record updates, and Visualforce pages.
Apex code can be initiated by Web service requests and from triggers on objects.

2. When should we use apex?


We use Apex if we want to:
Create Web services.
Create email services.
Perform complex validation over multiple objects.
Create complex business processes that are not supported by workflow.
Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object).
Attach custom logic to another operation, such as saving a record, so that it occurs whenever the operation is executed, regardless of
whether it originates in the user interface, a Visualforce page, or from SOAP API.

3.How does apex work?


All Apex runs entirely on-demand on the Lightning Platform. Developers write and save Apex code to the platform, and end users trigger the
execution of the Apex code via the user interface.
Apex is compiled, stored, and run entirely on the Lightning Platform

4.What is Developer Console?


Developer console is an integrated development environment (IDE)
It is a collection of tools we can use to create, debug and test application in salesforce Org

5. What are the tasks supported by developer Console?


Writing Code
Compiling Code
Debugging
Testing
Checking performance
SOQL Queries
Color Coding and auto complete.

6. What are the other IDE or code editors you use as a salesforce developer?
Visual Studio Code
Eclipse Force.com IDE
Welkin Suite – Paid
Illuminated Cloud (intelliJ Idea) – Paid

7. What are the different data types we have in salesforce?


Primitive
sObject
Collections
Enum

8.What are primitive data types?


The following are primitive data types
Integer
Double
Long
Date
Datetime
Sting
ID
Boolean

9. What are collections in salesforce?


List
Set
Map

10. What is an sObject?


sObject refers to any object that can be stored in the salesforce platform database.
Ex : Account, Lead, Opportunities, Invoice__c, payroll__c
Ex: Account a;
Ex: invoice__c inv;
Here “a” is an account sObject variable and “inv” is an invoice__c sobject variable

11. How to access sObjects fields?


sObjects fields can be accessed or changed with simple dot notation
Ex:
Account a = new account();
a.Name = ‘Acme’;

12. What are DML operations in apex?


Update
Insert
Delete
Ex:
Account a = new account();
……
…….
Update a;

13. What is single vs Bulk DML operation?


Updating one RECORD at a time is single dml operation whereas updating multiple RECORDS using list of sObject is
Bulk DML operation
Ex : Single DML Ex : Bulk DML

Account a = new accountA.name = ‘Acme’Insert a;Account a = Account a = new account();list aList = new list();A.name =
new accountA.name = ‘Google’Insert a; // Single DML ‘Acme’aList.add(a);a.Name = ‘Google’aList.add(a);Insert aList; //
bulk DML

14. Which DML is recommended ? SINGLE or BULK?


Performing BULK DML operations is the recommended way because it helps avoid hitting governor limits.

15. What is the difference between DML Statements vs Database Class Methods?
Apex offers two ways to perform DML operations
Using DML Statements
Using Database Class Methods
DML statements are more straightforward to use and result in failure of all the records in case one record fails
whereas with Database methods we can specify whether or not to allow for partial record processing if errors are
encountered.

We can do so by passing an additional second Boolean parameter.


Ex : DML Statement Ex : Database Class Methods

Account a = new account();a.Name = ‘ACME1’;Insert List aList = new List();alist.Add (new Account(Name
a;Ex : DML StatementAccount a = new =’acme1’));alist.Add(new Account (Name =
account();a.Name = ‘ACME2’;Insert a; ‘acme2’));Database.saveResult[ ] srList = Database.insert(aList, false);Here
false allows partial insert if there is an error.

16. Why do we use transaction Control statements?


We use transaction control statements in a scenario where we are executing multiple dml statements and we
want to roll back all the DML’s if one dml fails.

17. What are transaction Control statements?


Database.Savepoint
Database.rollback
are transaction control statements .
These are available in the Database Class.

18. Can you write sample code for a Transaction Control statement?
19. What is mixed DML operations error?
When we perform DML operations of setup object and non setup object in a transaction then we get mixed dml
operation error.
Example
Inserting an account object and user with role record in a same transaction

20. What are setup and non setup objects?


Setup Objects:
-User, UserRole etc
Non Setup Objects:
- Accounts, Leads, Opportunities

21. Can you tell me about a few objects which do not support DML operations?
There are few standard object which are also known as system objects which does not support DML operations
like
-BusinessHours
-BusinessProcess
-CategoryNode
-CurrencyType
-DatedConversionRate
-ProcessInstance
-Profile
-RecordType
-SelfServiceUser
-StaticResource
-Territory2 etc

22. What is a record locking or locking statement in salesforce?


In Apex, we can use FOR UPDATE to lock sObject records while they’re being updated in order to prevent race
conditions and other thread safety problems.
When an sObject record is locked, no other client or user is allowed to make updates either through code or
salesforce user interface.
23. What is the benefit of a Locking statement?
When we use a locking statement then we can perform logic on the records and make updates which guarantee
that the locked records won’t be changed by another client during the lock period.
The lock gets released when the transaction completes.

24. What are deadlocks?


Apex has the possibility of deadlocks as any other procedural programming language involving updates to
multiple database tables or rows.
A deadlock is a situation in which two or more transactions are waiting for one another to give up locks.

25. How to avoid deadlocks?


To avoid deadlocks , the apex runtime engine
First locks sObject parent records, then children.
Locks sObject records in order of ID when multiple records of the same type are being edited.
As a developer we should make sure we are not introducing deadlocks. We should verify using standard deadlock
avoidance techniques by accessing tables and rows in the same order from all locations in an application

26. What is dynamic Apex?


Dynamic apex enables us to create more flexible applications using describe information. By using dynamic apex,
we can write generic code that can be reused repeatedly with multiple sObjects.
Example : With dynamic objects we don’t have to explicitly declare the name of the object like account , lead or
opportunities. Based on the condition we can dynamically use any of the object and its fields
Example : We can also retrieve list of all the objects and its fields using dynamic apex etc

27. What is dynamic SOQL?


Dynamic SOQL refers to the creation of a SOQL string at runtime with Apex code.
Dynamic SOQL enables us to create more flexible applications.
Example : we can dynamically create a query based on multiple if else conditions.
Use Database query method to create dynamic SOQL

28. What is dynamic SOSL?


Dynamic SOSL refers to the creation of a SOSL string at runtime with apex code.
29. What is “With Sharing” and “Without Sharing” in apex?
“With Sharing” and “Without Sharing” keywords are used to ENFORCE or NOT ENFORCE users’ permissions and field-
level security .
Generally, apex runs in system administrator context , that means the current user’s permissions and field-level
security is not enforced. To enforce current users’ permission, we use “with sharing” keyword

30. What if we do not use “With Sharing” and “Without Sharing”?


By default, apex class runs “without sharing” i.e., in system admin context.

31. If apex runs “without sharing” then why do we have the keyword “without sharing”?
This is mostly used for inner class. Or in a situation we are calling methods from multiple classes Example 1

Class Name Sharing Result

Class A With sharing

Class B No sharing key


word used

Class A calls Both Class A and Class B run as “with Sharing” context because
Method in Class B parent class or calling class is “with sharing”

32. What is the impact of enforcing sharing rules i.e. using “with sharing” keyword on apex class?
SOQL and SOSL Queries : A query may return fewer rows than it would return in system context.
DML Operations : An operation may fail because the current user doesn’t have the correct permissions.

33. What is Apex Sharing?


Normally we share record using the following configurations
Record ownership
Role Hierarchy
Sharing rules
Manual Sharing
But Apex sharing is nothing but sharing the records programmatically. When all the above config options to share
the record does not work for our scenario then we use apex sharing
34. Can you elaborate how we can share records using apex sharing or programmatically?
Salesforce has provided a “Share” object for every object . All the sharing details of that object’s records can be
stored in share object
Ex:
Account object have AccountShare Object
Lead object have LeadShare Object
Opportunity object have Opportunity Share object
Invoice__c will have invoice_share object

35. Is there any other way we can enforce security apart from the “with sharing” keyword? Or How to enforce
security to a specific method or lines of code instead of the whole class?
We can use the following methods to enforce object level and field level security in apex code
isAccessable
isCreatable
Isupdatable
isDeletable
Example:

36. What are custom settings?


Custom settings are similar to custom objects. Developers can create a custom set of data and associate custom
data for an organization or profile or for a specific user.
All custom settings data is exposed in the application cache, which enables efficient access without the cost of
repeated SOQL queries to the database.
Formula fields , validation rules , flows, apex, and SOAP API can use this data.
Example:
A shipping application requires users to fill in the country codes for international deliveries. By creating a list
setting of all country codes, we can have quick access to this data without needing to query the database.

37. How many types of custom settings are there?


There are two types of custom settings available.
List Custom settings
Hierarchy Custom settings

38. What is Hierarchy Custom settings?


Hierarchy custom settings use a built-in hierarchical logic that lets us “personalize” settings for specific profiles or
users.
The hierarchy logic checks the organization, profile, and user settings for the current user and returns the most
specific or “lowest” value.
Example:
We have stored some data in custom setting, and we want to show the data based on users’ profile then we can
use hierarchy custom settings

39. What are Custom metadata or custom metadata types?


Custom metadata is similar to custom setting or object, but the only difference is the data stored in custom
metadata is also in the form of metadata.
A custom metadata type is an object that is used to define the structure for application metadata. The fields of
customer metadata types, and the values in the fields, consist only of metadata. The records of custom metadata
type are also metadata.

40. What is the advantage of custom metadata over custom settings? Or what is the difference between
custom metadata and custom settings?
Custom metadata stores data or records in the form of metadata so it is very handy or easy to migrate from one
org to another org. Custom metadata can be migrated to other orgs using any salesforce deployment tools.
Whereas Custom setting stores data in the form of data and its structure and field are in the form of metadata so
its structure and field can be deployed to the other orgs using deployment tools, but its data should be uploaded
using any data loader tools separately as any other data.

41. What are custom labels?


Custom labels are custom text values that can be accessed from apex classes, Visualforce pages, Lightning
components. Any field labels or error message are written in custom labels instead of hardcoding
Custom labels are generally used for two things in real time.
To avoid hard coding in the apex code, or visual force or Lightning components
To create multilingual applications

42. What is an anonymous Block?


An anonymous block is apex code that doesn’t get stored in the metadata, but that can be compiled and
executed.
If we want to run an ad hoc code and see the output we can use an anonymous window.
Goto → Developer Console → Debug → Open Execute Anonymous Window
43. Can you write a for loop to iterate a list of 10 accounts and set the Rating field to hot?

44. What is an apex class or a class?


Answer:
Similar to java , we can create classes in apex. A class is a template or blueprint from which objects are created.
Here the object is an instance of a class.
45. What are access modifiers we use for apex classes ?
Private
Public
global

46. Explain more about private access modifiers?


Private :
This is the default access modifier for inner class. I.e. if we don’t specify any access modifier for an inner class, it is
considered Private.
Top level classes can have either public or global but cannot have private access modifiers.
Top level classes can have a private access modifier if it is used with @isTest annotation.

47. Explain more about public and global access modifiers?


Public :
Public class is visible in the application or namespace.
Global :
global class is visible everywhere in the org.
A class with webservice method must be declared as global.
If a method or inner class is declared as global then the outer , top-level class must also be defined as global.

48. What is a constructor?


A constructor is a method which has the same name as the class name.
A constructor is a code that is invoked when an instance of a class is created.
A constructor is not mandatory to be created.
If a user doesn’t create a constructor, then a default constructor is created.
User defined constructor can be with arguments and without arguments.

49. What is the difference between static and instance methods in salesforce apex?
A static methods are the methods which can be called without the instance of a class whereas instance methods
are the methods which requires and instance of its class to be created before it can be called.
Example Static Method

This method can be called directly


String myCountry = UtilityClass.getCountry();
Example Instance Method

This method needs an instance to be created before calling


UtilityClass u = new UtilityClass();
String myCountry = u.getCountry();

50. What is interface?


An interface is like a class in which none of the methods have been implemented. The method signatures are
there, but the body of each method is empty.
To use an interface, another class must implement it by providing a body for all of the methods contained in the
interface.
51. What is a wrapper class in salesforce?
A wrapper class is an apex class with a collection of different data types. As the name suggests a wrapper class in
salesforce allows developers to combine different data types and use them for specific purposes.
A common wrapper class example is displaying the list of accounts on a visualforce page or lightning component
along with a checkbox. Here we are wrapping account records along with a Boolean which is used for checkbox.
52. What are annotations in apex? Or what are the annotations supported by apex?
An apex annotation modifies the way that a method or class is used. Annotations are defined with an initial @
symbol, followed by the appropriate keyword.
Apex supports the following annotations :
@AuraEnabled
@Deprecated
@Future
@isTest
@testSetup
@ InvocableMethod
@ InvocableVariable
@ JasonAccess
@ NamespaceAccessible
@ Readonly
@ RemoteAction
@ Suppresswarnings
@ Testvisible
@ RestResource
@ HttpGet
@ HttpPatch
@ HttpPost
@ HttpPut

53. What are some governor limits which are very frequently encountered in salesforce apex ?
Governor limits per transactions:

Description Synchronous Limit Asynchronous Limit

Total number of SOQL queries issued 100 200

Total number of records retrieved by SOQL 50,000 50,000


queries

Total number of records retrieved by 10,000 10,000


Database.getQueryLocator

Total number of SOSL queries issued 20 20

Total number of records retrieved by a 2000 2000


single SOSL query

More governour limits

Description Synchronous Limit Asynchronous Limit

Total number of DML statements issued 150 150

Maximum number of methods with the 50 0 in batch and future contexts;1 in


future annotation allowed per Apex queueable context
invocation

Maximum CPU time on the Salesforce 10,000 milliseconds 60,000 milliseconds


servers5

Maximum number of EventBus.publish calls 150 150


for platform events configured to publish
immediately

54. What is debugging and How do you debug apex ?


Debugging can be defined as the process of finding the root cause of a problem or a bug in a code and fixing it.
Salesforce provides debug logs to debug apex . We can also access debug logs from the developer console.

55. Can you explain the steps to debug the code in apex?
Step 1 : Enable the debug logs . To enable the debug logs goto setup → Quick find Debug logs →
Click New “Select the users for which you want to enable debug logs”
Enter “Start Date”
Enter “Expiration Date”
Enter “Debug Level “
Step 2 : Run the functionality for which you want to debug .
Step 3 : Go back to the debug logs from setup and Open the debug logs for that particular user.
Step 4 : Analyze the debug logs to find the issue.

56. What does the debug log file contain or What information does the debug log provide?
Debug log provides the information about the following.
Database changes
HTTP callouts
Apex errors
Resources used by Apex
Automated workflow processes, such as:
Workflow rules
Assignment rules
Approval processes
Validation rules
Process builder
FLOWS
Note : The debug log does not include information from actions triggered by time-based workflows.

57. Why do we use system.debug()?


System.debug is used to print information of a specific line of code in apex or triggers.
Apart from the general debug information, debug logs contains the information from system.debug statements.
Ex: If we want to see if a particular list or set is updated with right values after the logic is processed then we write
system.debug to see that list
System.debug(‘accList ⇒’ + accList);

58. What is an exception and what happens when an exception occurs?


Exception is an error or event that disrupts the normal flow of code execution. When an exception occurs , code
execution halts.

59. What are exception statements?


There are two exception statements:
Throw statements : Used to generate exception
Try, catch, and finally : Used to gracefully recover from an exception.

60. Name a few built-in exception types?


DMLExcption
ListExcption
NullPointerException
QueryException
SObjectException

61. Provide an example of handling generic exceptions as well as specific exceptions using built-in exception
types?
62. Can you write sample code for a custom exception?

63. Can we handle governors limit exceptions using try catch ?


NO. When we encounter governor limits, code executions halts immediately and this cannot be handled using
exception handling .

64. What is a trigger?


Apex triggers allows us to perform custom actions before or after changes to salesforce records, such as insertion,
updates or deletions.
Apex trigger is an apex code that executes before or after changes to the salesforce records , such as insertion,
updates or deletions.

65. Explain the different types of triggers ?


There are two types of triggers:
Before Triggers : It is used to update or validate record values before they’re saved to the database.
After triggers : It is used to access field values that are set by the system (such as a record’s id or lastModifedDate
field) , and to affect changes in other records, like updating the records of the same object or other objects. The
records that fire the after trigger are read-only

66. What are the different types of trigger events in salesforce?


Before insert
Before update
Before delete
Before undelete
After insert
After update
After delete
After undelete
Note : Before undelete event does not exist.

67. Can you write trigger syntax and an example?


Syntax

where trigger_events can be a comma-separated list of one or more events

Variable Usage

isExecuting Returns true if the current context for the Apex code is a trigger, not a Visualforce
page, a Web service, or an executeanonymous() API call.

isInsert Returns true if this trigger was fired due to an insert operation, from the Salesforce
user interface, Apex, or the API.

isUpdate Returns true if this trigger was fired due to an update operation, from the Salesforce
user interface, Apex, or the API.

isDelete Returns true if this trigger was fired due to a delete operation, from the Salesforce
user interface, Apex, or the API.

isBefore Returns true if this trigger was fired before any record was saved.

isAfter Returns true if this trigger was fired after all records were saved.

isUndelete Returns true if this trigger was fired after a record is recovered from the Recycle Bin.
This recovery can occur after an undelete operation from the Salesforce user
interface, Apex, or the API.

new Returns a list of the new versions of the sObject records.This sObject list is only
available in insert, update, and undelete triggers, and the records can only be
modified in before triggers.
newMap A map of IDs to the new versions of the sObject records.This map is only available in
before update, after insert, after update, and after undelete triggers.

old Returns a list of the old versions of the sObject records.This sObject list is only
available in update and delete triggers.

oldMap A map of IDs to the old versions of the sObject records.This map is only available in
update and delete triggers.

operationType Returns an enum of type System.TriggerOperation corresponding to the current


operation.Possible values of the System.TriggerOperation enum are: BEFORE_INSERT,
BEFORE_UPDATE, BEFORE_DELETE,AFTER_INSERT, AFTER_UPDATE, AFTER_DELETE, and
AFTER_UNDELETE. If you vary your programming logic based on different trigger types,
consider using the switch statement with different permutations of unique trigger
execution enum states.

size The total number of records in a trigger invocation, both old and new.

Example

68. What are Trigger context variables?


All triggers define implicit variables that allow developers to access run-time context. These variables are
contained in the system.Trigger Class.

Sample Trigger for trigger context variables


69. What is the difference between Trigger.New and Trigger.Old?
Trigger.new returns a list of the new versions of the sObject records whereas Trigger.Old returns a list of the old
versions of the sObject records.
Trigger.new is available in insert, update, and undelete triggers whereas Trigger.Old is only available in update and
delete triggers.

70. What is the difference between Trigger.New and Trigger.NewMap?


Trigger.new returns a list of the new versions of the sObject records whereas Trigger the newMap returns a map of
IDs to the new versions of the sObject records.

71. Availability matrix for Trigger.New, Trigger.NewMap, Trigger.Old and Trigger.Old Map?

Trigger Event Trigger.New Trigger.Old Trigger.NewMap Trigger.OldMap


Before Insert Yes No No No
72.
Before Update Yes Yes Yes Yes Can
we
Before Delete No Yes No Yes call

After Insert Yes No Yes No

After Update Yes Yes Yes Yes

After Delete No Yes No Yes

After Undelete Yes No Yes No

batch apex in trigger?


Yes, we can call batch apex in trigger.

73. Can a trigger make a call to the apex callout method?


We can call a callout method in apex trigger but the only condition is that it has to be an asynchronous callout
because the trigger flow cannot wait on the response received by the callout method.
We should use a future method to call the callout method in triggers.

74. Can we call a scheduled class from the trigger?


Yes we can but it is not recommended.

75. What is a recursive Trigger?


A recursive trigger is the one which calls itself over and over again and eventually exceeds the maximum trigger
depth limit.

76. How to avoid the recursive trigger?


To avoid recursive triggers we can create a class with a static Boolean variable and default it to true. In the trigger,
before executing the code check if the static variable is true or not . Once executed, make the variable false.
So, when the trigger tries to execute next time the static variable will be false and hence it will not execute the
trigger again.
But be mindful before implementing a recursive trigger as sometimes we might need a trigger to execute more
than one.

77. How to show the error messages on the page or on the field using Trigger. (similar to validation rules error) ?
We can use addError method in triggers to show the message on the page or on the field
Example
78. When an account is created then automatically 3 contacts should be created .On what object we should
write the trigger ?
Trigger should be written on Account

79. When an account is created then automatically 3 contacts should be created. What type of trigger should it
be? (Before or After)
After insert.

80. How many triggers can we create on an object?


We can create as many triggers as we want on an object but it is recommended to create one trigger per object.

81. What are bulk triggers ? or How to bulkify triggers?


A trigger handling multiple records at a time is a bulk trigger.
All triggers are bulk triggers by default, and can process multiple records at a time. We should always write
triggers which can handle more than one record at a time.

82. What are trigger handlers?


Trigger handler is an apex class to handle the logic of a trigger. It is used to provide a better way of writing
complex logic that’s required for trigger code and also to avoid creating more than one trigger per object.
When we write the trigger handler class then the execution or trigger point starts in the trigger code but the actual
logic is written in handler class.
Use the Trigger handler to write all the logic or code and create your triggers as logic-less triggers.
Trigger Code:

Trigger Handler Class Code:

83. What are helper classes?


A helper class is also a class which is used to write common methods which can be used by multiple other
classes.
Example:
To find the weather of a city
Calculate the tax for a salary/income
To find the country of a city

84. What are triggers best practices?


1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object,
you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be
re-used anywhere else in your org.

3) Context-Specific Handler Methods


Create context-specific handler methods in Trigger handlers

4) Bulkify your Code


Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a
time.

5) Avoid SOQL Queries or DML statements inside FOR Loops


An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this
trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops


It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of
using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid
governor limits

7) Querying Large Data Sets


The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of
queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process
multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately


It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for
asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous
and asynchronous Apex can be found

9) Avoid Hardcoding IDs


When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange
packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between
environments, the logic can dynamically identify the proper data to operate against and not fail

86. What is asynchronous apex?


Asynchronous Apex is used to run processes in a separate thread, at a later time.
An asynchronous process is a process or function that executes a task “in the background” without the user
having to wait for the task to finish.
87. What are different asynchronous features available in Salesforce?
Future Methods
Batch Apex
Scheduled Apex
Queueable Apex

88.When to use asynchronous apex?

Asynchronous When to use


apex feature

Future When we make callouts to external web serviceWhen we have a long-running method
Methods and need to prevent delaying an apex transactionTo segregate DML operations and
bypass the mixed save DML error

Batch Apex For long-running jobs with large data volumes that need to be performed in batches, such
as database maintenance jobsFor jobs that need larger query results than regular
transactions allow

Scheduled To schedule an apex class to run on a specific schedule


Apex

Queueable To start a long-running operation and get an ID for the jobTo pass complex types to job
Apex (like sobjects or custom apex types etc)To chain jobs

89. What is a future method?


Future method is one of the asynchronous apex types which runs in the background or in a separate thread.
Future method is same as any other apex method with @future annotation
With future methods we get some increased governors limits lie SOQL query limits and heap size limits.
Future methods must be static and can only return void type.

90. Does the future method support all the data types as parameters or arguments?
No, future methods only support primitive data types or collections and do not support sObjects as arguments.

91. Why does the future method not support sObject data types as arguments?
The reason why sObject can’t be passed as arguments to future methods is because the sObject might change
between the time we call the method and the time it executes. In this case ,the future method will get the old
sObject values and might overwrite them.

92. What if we have the requirement to work with sObjects in the future method?
To work with sObjects that already exist in the database, pass the sObject ID instead (or collection of IDs) and use
the ID to perform a query for the most up-to-date record.

93. Can we make a callout to external web services using future methods and how to do it?
Yes we can make a callout to external web services using future methods . Use an extra parameter (callout =true)
with future annotation
Like @future(callout=true)

94. Write a sample code utilizing a future method?


The following code uses a normal method to insert and account record and future method to insert user record.
This can also be an example to avoid mixed dml error.
Main method:
Future Method

95. Can we call a future method from another future method?


No, we cannot call a future method from another future method.

96. Can we call future methods from a batch job?


No, we cannot call future methods from a batch job.

97. Can we call future methods from a Trigger?


Yes, we can call future methods from a trigger.

98. Given a scenario where we have written a future call in the Opportunity Trigger update operation. And we
have a batch job running on opportunity records and updates the records, Does the future call be invoked after
the update?
Since we are in batch context, the trigger will run in the same context (i.e batch context). So as soon as the
opportunity records get updated though the batch process and then the future method gets called from the
trigger then the trigger would throw an exception saying “Future method cannot be called from a future or batch
method” as future method cannot be invoked from future or batch method execution context.

99. How can we avoid the above exception?


The best way to avoid this exception is to write a code in such a way that the future method does not gets
executed from the batch job call or another future method call.
100. What if we want to call a future method from a future method, is there any workaround?
As the future method cannot be called from another future method then as a work around we can call a
webservice that has future invocation.
Like future method → web service → future method.

101. Can we trace or track the execution of future methods?


We can trace the future method from setup → apex Jobs
But if it is in the queue and resources are not available then it wont show up in the apex jobs. So we can query the
asyncApexJob object to get the status.
However, future methods do not have an ID, so we can’t trace it directly. We can use another filter such as
MethodName , or JobType to find the required job.

102. How to write the test class for a future method?


To test methods defined with the future annotation, call the class containing the method in a StartTest(),
stopTest() code block.
All asynchronous calls made after the startTest() method are collected by the system, When stopTest() is
executed , all asynchronous processes are run synchronously.

103. What are some limitations of future methods?


It is not recommended to process a large number of records.
It supports only primitive data types.
Tracing a future job is not straightforward.
We cannot call future methods from a batch and future context. However one call from a queueable context is
allowed.

104. What is a batch apex?


Batch apex is one of the asynchronous apex features or type.
Batch Apex is used to run large jobs (think thousands or millions of records!) that would exceed normal processing
limits.
Using Batch Apex, we can process records asynchronously in batches (hence the name, “Batch Apex”) to stay
within platform limits.
If we have a lot of records to process, for example, data cleansing or archiving, Batch Apex is probably the solution

105. How to use a batch apex?


To use batch apex, write an apex class that implements the salesforce provided interface Database.Batchable
and then invoke the class programmatically.

106. Why do we implement Database.batchable interface or what happens when we implement


Database.batchable interface?
Database.Batchable interface contains three methods that must be implemented.
Start()
Execute()
Finish()
These three methods are mandatory if we use Database.Batchable interface. If we do not implement any one of
the three methods then the class throws an error.

107. Can you explain about three methods of batch apex?


Start method: It is used to collect the records of objects to pass to the interface method “execute”, call the start
method at the beginning of a batch apex job. This method returns either a Database.QueryLocator object or
an iterable that contains the records or objects passed to the job
Execute method: It is used to do the required processing for each chunk of data. This method is called for each
batch of records that you pass to it.
Batches of records tend to execute in the order in which they’re received from the “start” method. However, the
order in which batches or records execute depends on various factors. The order of execution isn’t guaranteed.
Finish method: This method is called after all batches are processed. It can be used to send confirmation emails or
execute post-processing operations.

108. Can you write a sample Batch apex class?

109. Explain about Database.Querylocator in batch apex?


Database.querylocator can be used for simple query (SELECT) to generate the scope of the objects in the batch
job.
With Querylocator the governor limit for the total number of records retrieved by SOQL queries is bypassed.
When using querylocator the maximum number of records can be retrieved is up to 50 millions.

110. Explain about Iterable in batch apex?


Iterable is used when we have to create a more complex scope for the batch job.
Example if the batch class needs to operate on data obtained from two unrelated objects, then we can create a
custom iterable class and return combined data from both objects as a list of iterable from start method.
With Iterable we can pass both the objects or records to the execute method for processing.
With iterable the governor limit for the total number for records retrieved by SOQL queries is still enforced which is
up to 50 thousand records

111. How to invoke a batch Class?


To invoke a batch class, simply instantiate it and then call Database.executeBAtch with the instance
Optionally we can pass a second scope parameter to specify the number of records that should be passed into
the execute method for each batch.

112. Can we track the progress of the batch job?


Yes. Each batch apex invocation creates an AsyncApexJob record so that we can track the job’s progress.
We can view the progress via SOQL or manage you job in the Apex Job Queue,
SOQL :

113. What is the maximum and minimum size of the optional parameter “scope”?
Scope parameter can accept a max value of 2000.
Salesforce chunks the records returned by the QueryLocator into smaller batches of up to 2000 records.
If the “start” method of the batch class returns an iterable, the scope parameter values have no upper limit.
The optimal scope size is a factor of 2000 , for example 100, 200, 400 and so on.
The minimum size of the scope parameter is “1”

114. What is the batch size if we don’t use optional scope parameters?
The default batch size is 200 records.

115. Do the batches of records execute in the order they are received from the start method?
No . Batches of records are not guaranteed to execute in the order they are received from the start method.

116. What is Database.BatchableContext?


All methods (start, execute and finish methods) in the batch apex class require a reference or parameter to the
Database.BatchableContext object.
Database.Batchablecontext object is used to track the progress of the batch job.
getJobId is the instance method with Database.BatchableContext object
We can use getJobId and query asyncApexJob to get the status of the batch job.

117. Can we Query related records or child records using Database.QueryLocator?


Yes. We can perform subquery to get the related records but with a subquery the batch job processing will be
slower.
It is recommended to perform the subquery separately from within the execute method which allows the batch
job to run faster.

118. Can we use FOR UPDATE in SOQL using Database.QueryLocator?


No, we cannot use FOR UPDATE in SOQL using Database.QueryLocator, as it will throw an exception “Locking is
implied for each batch execution and therefore FOR UPDATE should not be specified”
The reason we cannot use it is , if we query the entire object (like all account records) using SELECT and FOR
UPDATE then we will lock all the account records as long as the batch is active.
119. What is “state” in batch apex? Or What is Database.Stateful?
Each execution of batch apex is considered a discrete transaction. For example , a batch apex job that contains
1000 records and is executed without the option parameters is considered five transactions of 200 records each.
If we specify database.stateful in the class definition , we can maintain state across these transactions.
When using Database.stateful, only instance member variables retain their values between transactions. Static
member variables don’t retain their values and are reset between transactions.

120. Can you give an example of maintaining the state of a batch apex?
We can maintain the state of a batch apex for counting or summarizing records as they’re processed.
For example, suppose our job processed opportunity records. We could define a method in “execute” to aggregate
totals of the opportunity amounts as they were processed.

121. What will happen if we don’t use Database.Stateful?


All static and instance member variables are set back to their original values or all the variables are reset for each
transaction of the batch.

122. Can you write a sample batch apex with Database.Stateful?

123. Can we callouts in batch apex?


Yes, we can callouts in batch apex. To use callout in batch apex, we have to specify Database.Callouts in the class
definition.

124. Given a scenario , we have to process a batch apex with 1000 records with 200 records in each transaction
and the last transaction failed while doing the DML operation. What will happen to the processed records?
If all the first 4 transactions succeed but the last fails, then the database updates made in the first 4 transactions
are not rolled back.
Since the batch size is 200, the first 4 batches will be processed completely, and all the data will be committed to
the database. In the last batch, if we are committing records using normal DML statements like insert, update then
the whole batch will rollback. So, the records from 801 to 1000 will not be processed.
If we use the database DML operations like Database.insert with AllorNone as false, then a partial commit can
happen and only the failed record will not be processed in that batch and the rest of the records will be processed.

125. Can we call a future method from a Batch apex?


No, we cannot call a future method from a batch apex.

126. How to stop or abort a Batch job?


Get the id of the batch job by running a SOQL query on AsyncApexJob and use a system.aboartJob(jobId) to abort
the job.

127. What is the apex flex queue?


Normally an org can process 5 jobs at a time and if we add more then 5 jobs at a time then it goes into the apex
flex queue.
Let’s say we have added 15 jobs at a time then 5 jobs will be processed, and 20 jobs will go into the apex flex
queue.

128. What is the maximum limit of the apex flex queue?


Apex flex queue can hold up to 100 jobs at a time.

129. What would happen if we added more than 100 jobs like 125 jobs at a time ?
The first 5 jobs will be processed and next 100 will be queued and the rest of the 20 jobs will be rejected or not
added into the queue.

130. What will be the status of the job in the apex flex queue?
All the jobs in the apex flex queue will have status as “Holding”

131. Can we change the order of already queued Batch jobs?


Only jobs having status as “Holding” can be moved. It can be done though UI of apex flex queue or we can use
Apex Flex Queue Methods.
132. How can we schedule a batch apex?
We can schedule a Batch apex using system.scheduleBatch Method. We can schedule a batch for once at a
future time. This method returns the scheduled job ID also called as CronTrigger Id

133. How can we test a batch apex?


When testing batch apex, we can test only one execution of the “execute” method. So, use the scope parameter of
the “executeBatch” method to limit the number of records passed into the execute method to ensure that we
aren’t running into governor limits.
Use the test methods startTest() and StopTest() around the executeBatch method to ensure that it finishes before
continuing tests.
All asynchronous calls made after the startTest() method are collected by the system. When StopTest() is
executed, all asynchronous processes are run synchronously. If we don’t include the executeBatch method within
the starTest() and StopTest() methods, the batch job executes at the end of the test method.

134. What is Scheduled Apex?


Scheduled apex is all about running or invoking apex class which will run at a specific time. To schedule an apex
class, we need to implement a schedulable interface.

135. When should we use scheduled apex?


Here are few example of scheduled apex use case
To update the records of an object periodically . Example update opportunity status to close-lost if it is not
updated in the last 90 days.
To sync the external system every night – Example run a scheduled job every night to sync the data from
salesforce to external system every night
One off update to the record after data migration . Example after data migration from other system we can run a
schedule job one off to updated the records based on some logic
And many more….

136. Which interface should be implemented for schedulable class?


To schedule an apex class, it should implement salesforce provided interface “Schedulable”

137. Is there any mandatory method(s) that must be implemented?


execute () methods must be implemented for scheduled apex. And the execute method must be declared as
global or public.
138. What is schedulableContext?
It is a parameter for the execute method of a class that implements a schedulable interface. SchedulableContext
contains the scheduled job ID which can be retrieved using the getTriggerID method.
We can use getTriggerId to track the progress of a scheduled job through a query on CronTrigger.
We can also monitor it from Setup → Scheduled job

139. What is CronTrigger?


CronTrigger is an object . When we schedule an apex class, a cronTrigger record is created that represents the
scheduled job. We can query CronTrigger objects to obtain more information about the job like the number of
times the job has run, and date and time when the job is scheduled to run again.

140. How can we schedule the apex class?


There are two ways to schedule an apex class.
Using developer console : Write the following code in an anonymous window and run it to schedule it.

Here:
10 represents seconds
30 represents minutes
8 represents hour of the day
15 represents 15th day of month
6 represents month of the year
? Specifies no specific value. This option is only available for Day_of_month and Day_of_week. It’s typically used
when specifying a value for one and not the other.
From the UI
From Setup , search apex in quick find box then Select apex classes
Go to Setup → apex classes
We will see a “Schedule apex” button. We can set up the timing from there
141. What is CORN_EXP?

Special Description
character

, Delimits values. For example, use JAN, MAR, APR to specify more than one month.

– Specifies a range. For example, use JAN-MAR to specify more than one month.

* Specifies all values. For example, if Month is specified as *, the job is scheduled for every
month.

? Specifies no specific value. This option is only available for Day_of_month and
Day_of_week. It’s typically used when specifying a value for one and not the other.

/ Specifies increments. The number before the slash specifies when the intervals will begin,
and the number after the slash is the interval amount. For example, if you specify 1/5 for
Day_of_month, the Apex class runs every fifth day of the month, starting on the first of the
month.

L Specifies the end of a range (last). This option is only available for Day_of_month and
Day_of_week. When used with Day of month, L always means the last day of the month,
such as January 31, February 29 (for leap years), and so on. When used with Day_of_week by
itself, it always means 7 or SAT. When used with a Day_of_week value, it means the last of
that type of day in the month. For example, if you specify 2L, you’re specifying the last
Monday of the month. Don’t use a range of values with L as the results can be unexpected.

W Specifies the nearest weekday (Monday-Friday) of the given day. This option is only
available for Day_of_month. For example, if you specify 20W, and the 20th is a Saturday, the
class runs on the 19th. If you specify 1W, and the first is a Saturday, the class doesn’t run in the
previous month, but on the third, which is the following Monday.
# Specifies the nth day of the month, in the format weekday#day_of_month. This option is
only available for Day_of_week. The number before the # specifies weekday (SUN-SAT). The
number after the # specifies the day of the month. For example, specifying 2#1 means the
class runs on the first Monday of every month.

CORN_EXP is called as Cron Expression and it is used to define the scheduling time it has 7 parameters including
one optional year parameter
An expression is written in the form of “Seconds, Minutes, Hours, Day_of_month, Day_of_week, optional_year.

142. Can you explain or elaborate all the special characters used in CORN_EXP?
143. Can you explain or elaborate all the values used in CORN_EXP?

Name Values Special Characters

Seconds 0–59 None

Minutes 0–59 None

Hours 0–23 ,–*/

Day_of_month 1–31 ,–*?/LW

Month 1–12 or ,–*/


the following:
JAN
FEB
MAR
APR
MAY
JUN
JUL
AUG
SEP
OCT
NOV
DEC

Day_of_week 1–7 or ,–*?/L#


the following:
SUN
MON
TUE
WED
THU
FRI
SAT

optional_year null or 1970–2099 ,–*/


144. Can you write some examples of how to use the expressions or CORN_EXP?

Expression Description

0 0 13 * * ? Class runs every day at 1 PM

0 0 22 ? * 6L Class runs the last Friday of every month at 10 PM.

0 0 10 ? * MON-FRI Class runs Monday through Friday at 10 AM.

0 0 20 * * ? 2010 Class runs every day at 8 PM during the year 2010.

145. Which all types of classes or asynchronous processes we can schedule?


We can schedule all of them like
Batch Apex – We can call a batch class from scheduled apex
Future method – We can call future method from scheduled apex
Queueable apex – we can call a queueable apex from scheduled apex.

146. Among Batch apex, Future method and Queueable apex , which one can cause issues if we schedule them?
If we call future methods from scheduled apex then it can cause some issues.
Because the future method does not guarantee its execution on time. So, tracking is not possible as we lose
transaction control as scheduled apex gets over as soon as it fires the future method.
There is a limit to the number of future calls based on the number of licenses of our org.

147. Can you update the class or any classes referenced in a scheduled job?
If there are one or more active scheduled jobs for an apex class, we cannot update the class or any classes
referenced by the apex class though the salesforce user interface (like updating the apex class within the
salesforce UI).
However, you can update the class in the sandbox and deploy the class in production with active scheduled job
by using metadata API

148. What is the maximum number of jobs that can be scheduled at a given time?
We can only have 100 scheduled apex jobs at a time.

149. How to count the number of scheduled jobs ?


SELECT COUNT() FROM CronTrigger where CronJobDetails.JobType = ‘7’
Here CronJobDetails.JobType = ‘7’ represents scheduled apex

150. Does scheduled apex support Callout?


No, Scheduled apex does not support synchronous web service callouts.

151. If callout is not supported in scheduled apex then what is the alternate way to callout from scheduled apex?
There are two ways to callout from scheduled apex. We should make asynchronous callouts
Using future method : user future method with callout like @future(callout=true) and call this method from
scheduled apex.
Create a batch apex with callouts (callouts are supported in batch apex) and create a scheduled apex which
executes the batch job.
152. Can you tell me about some best practices for scheduled apex?
If we are planning to schedule a class from a trigger. We must be able to guarantee that the triggers won’t add
more scheduled classes than the limit.
Though it’s possible to do additional processing in the execute method, we recommend that all processing take
place in a separate class.
Synchronous web service callouts are not supported from scheduled apex, to make asynchronous callouts use
@feature or Batch apex.

153. What is a queueable apex?


Queueable apex is one of the types of asynchronous apex. It is similar to @future method. But queueable apex
provide these additional benefits
Getting an Id for your job : When we submit the job using the system.enqueueJob method it returns the ID of the
new job.
Using non-primitive types : Our queueable class can contain member variables of non-primitive data types such
as sObjects or custom apex types. Those objects can be accessed when the job executes.
Chaining jobs: we can chain jobs to another job by starting a second job from a running job. Chaining jobs is
useful if our process depends on another process to have run first.

154. Which interface is implemented for Queueable class?


Queueable class implements Queueable

155. Can you write the sample code for a queueable class?

You might also like