Professional Documents
Culture Documents
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.
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
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
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.
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.
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
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
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 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.
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:
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.
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
53. What are some governor limits which are very frequently encountered in salesforce apex ?
Governor limits per transactions:
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.
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?
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.
size The total number of records in a trigger invocation, both old and new.
Example
71. Availability matrix for Trigger.New, Trigger.NewMap, Trigger.Old and Trigger.Old Map?
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.
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.
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
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
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)
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.
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.
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.
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.
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”
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?
Expression Description
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.
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.
155. Can you write the sample code for a queueable class?