[go: up one dir, main page]

0% found this document useful (0 votes)
30 views92 pages

Salesforce Interview Questions

The document provides an overview of Salesforce concepts, including sandboxes, cloud computing, and various service models like IaaS, PaaS, and SaaS. It details Salesforce object relationships, sharing rules, and automation tools such as Flow and Apex, along with best practices for their use. Additionally, it covers Lightning components, communication methods, and web services in the context of Salesforce development and integration.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views92 pages

Salesforce Interview Questions

The document provides an overview of Salesforce concepts, including sandboxes, cloud computing, and various service models like IaaS, PaaS, and SaaS. It details Salesforce object relationships, sharing rules, and automation tools such as Flow and Apex, along with best practices for their use. Additionally, it covers Lightning components, communication methods, and web services in the context of Salesforce development and integration.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

1. What is Sandbox and the Type of Sandbox in Salesforce?

A Salesforce sandbox is an isolated copy of your organization’s production environment


that is used for development and testing purposes. Your production environment has
your live data and active users logging in. A Salesforce sandbox will always include a
copy of your production organization’s metadata

Types of Sandbox in Salesforce

There are 4 types of Salesforce sandbox environments.

1. Developer Sandbox

2. Developer Pro Sandbox

3. Partial Copy

4. Full Sandbox

2. What is Cloud Computing?

Cloud computing is a way to access information and applications online instead of


having to build, manage, and maintain them on your own hard drive or servers. It’s fast,
efficient, and secure.

Simply put, cloud computing is a way of accessing services on the internet instead of on
your computer. You can use the cloud to access applications, data, and development
tools from virtually anywhere. Whether you’re working on your phone from a crowded
train in Chicago or on your laptop at a hotel in Hong Kong, you can access the same
information because it all lives online.

3. What is Iaas?

IaaS stands for Infrastructure as a service: A cloud service provider owns and
manages the hardware upon which your software stack runs. That includes servers,
networking, and storage. This can be a great cost-reduction strategy if you’d like to avoid
purchasing and maintaining infrastructure.
In this type of service, you will get the Virtual System that can be connected using the
internet. Where you can install any Software even in some service providers you can
install the operating system.

4. What is PaaS?

PaaS stands for Platform as a service: In this type of service, you get a development
platform bundled with all the types of software preinstalled. You will then have to write
and execute all your codes in a remote server by some mechanism.
5. What is Saas?

SaaS stands for Software as a service: It offers the most support and is the simplest of
all delivery models for the end user. Chances are that you already use it in your
organization. This is the highest level of service in which everything is provided from
hardware to software to already build applications.

Salesforce Developer Configuration Interview Question and Answers

Let’s see the Salesforce platform configuration-related interview questions and


answers:

6. What is the type of object relationship in Salesforce?

There are six types of object relationships in Salesforce.

1. Lookup Relationships

2. Master-Detail Relationship

3. Many-to-Many Relationships (Junction Object)

4. Self Relationship

5. External Relationships

6. Hierarchical Relationships

7. What is Junction Object in Salesforce?

A junction object is a custom object with two master-detail relationships, and it is the
key to making a many-to-many relationship.

8. What is the difference between Roles and Profiles?

Profiles help to control object privileges such as CRED (Create, Read, Edit, Delete).
They also contain system permissions that a user can carry out such as exporting data.
Profile used for object level and Field level access. It is mandatory for all Users.

Roles on the other hand help with sharing records across an organization. They work in
a hierarchical fashion, giving users access to records that are owned by people lower
down in the hierarchy. Roles used for Record level access. It is not mandatory for all
Users.

9. How many ways we have in Salesforce for Sharing?

There are 20+ ways to share record access in Salesforce.

1. Profile/ Permission set Object level CRED access

2. View All and Modify All permission on the profile or permission set
3. Profile level System Permission.

4. Organization-Wide Default (OWD)

5. Record Ownership

6. Role Hierarchy

7. Case Team, Account Team, and Opportunity Team.

8. Queues

9. Sharing Rules

10. Groups

11. Territory Management

12. Sharing Sets

13. Sharing Groups

14. Super User Access

15. Manual Sharing

16. Apex Sharing

17. Visualforce with Apex

18. Implicit Sharing

19. Master-Detail Relationship

20. External Account Hierarchy

10. What are Sharing Rules?

Sharing rules in Salesforce are used to create automatic exceptions to the Organization-
Wide Default settings for the users who do not own the record.

They should be applied to the objects whose org-wide defaults are set to Public Read-
only or Private because sharing rules can only extend the access they cannot restrict
the access provided by Organization-wide defaults.

There are 2 types of Sharing Rules in Salesforce based on which records to be shared:

• Owner Based

• Criteria Based

11. How do we do Manual Sharing?


The Manual sharing button allows users to share records with others with one button
click. Sometimes we encounter a scenario where individual users want to share their
records with another colleague (user). In that case, manual sharing is the best option.

12. What is Apex Sharing?

There are situations where the business requirement is too complex and standard
sharing rules provided by the Salesforce will not work. In that case we can use the Apex
Sharing.

To access sharing programmatically, you must use the share object associated with the
standard or custom object for which you want to share. For example, AccountShare is
the sharing object for the Account object and for MyCustomObject it should be like
MyCustomObject__Share. Here is sample code. Learn more about Apex Sharing.

public static boolean apexSharingDemo(Id recordId, Id userOrGroupId){

MyCustomObject__Share myCustomObject = new MyCustomObject__Share();

myCustomObject.ParentId = recordId;

myCustomObject.UserOrGroupId = userOrGroupId;

myCustomObject.AccessLevel = 'Read';

myCustomObject.RowCause =
Schema.MyCustomObject__Share.RowCause.Manual;

Database.SaveResult[] jobShareInsertResult =
Database.insert(myCustomObject,false);

Learn more about Sharing and Visibility here.

13. Type of Flow in Salesforce?

Flow is an automation tool provided by Salesforce which can be used to perform various
tasks like Sending Emails, Posting chatter, Sending custom Notifications &, etc using
clicks instead of code. Check Salesforce Flow Builder training if you are new.

Types of flows in Salesforce


1. Screen Flow: With Screen Flow you can create a custom UI (user interface) and
guide users through a business process that can be launched from Lightning
Pages, Experience Cloud (previously known as Community Cloud), quick actions
and more.

2. Record-Triggered Flow: This Flow launches when is record is created, updated,


or deleted. So far, we have used Apex triggers for these automations some of
which can now be done using Flows.

3. Scheduled-Triggered Flow: This flow launches at the specified time and


frequency for each record in a batch. Traditionally we have met this kind of
requirement using Apex batch jobs.

4. Platform Event Flow: Launches when a platform event message is received. For
example, you can pump the data from an external system in Platform Events and
then use Flows to split and save the records in different objects.

5. Auto launched Flow: Launches when invoked by Apex, Process Builder or even
REST API

14. When to use Salesforce Flow and Apex?

Try not to mix Apex, Process Builders, Workflow Rules, and Record-Triggered flows. In
general, you should choose one automation tool per object.

Salesforce Flow Apex

let declarative tools handle non-DML activities like email alerts and in-app separate DML activity a
alerts Apex

15. Best practices for Salesforce Flow?


Check out the Apex hour blog post to learn about Best practices for Salesforce Flow.

1. Always! Plan Before You Build

2. “One Record-Triggered Flow” Per Object – Per Type

3. No DML Statement in Loops

4. Use the Advanced Technique to Merge Decision Node

5. Build Reusable Flow(s) – Subflow(s)

6. Don’t Create Flow for Everything

7. Build in a test/Sandbox environment

8. Supercharge Flow with Invocable Apex

9. Don’t Hardcode IDs, Query for them!

10. Dont mix Trigger, Process Builder, Flow and Record Trigger Flow

11. Handle Errors with Fault Paths

12. Exception handling in flow using Platform Events

13. Use Debug Log to Check Why a Flow Fails at Runtime

14. Flow Naming Conventions

Salesforce Developer Apex Interview Question and Answers

Let’s see the Salesforce platform Apex interview questions and answers:

16. What is Apex? and when to use Apex over Flow?

Apex is a programming language developed by Salesforce. It is a strongly typed, object-


oriented programming language that allows developers to execute flow and transaction
control statements on the Salesforce platform.

One common approach is to separate DML activity and offload it to Apex, and let
declarative tools handle non-DML activities like email alerts and in-app alerts — just be
careful and ensure none of your Apex conflicts.

17. What are Apex Best practices in Salesforce?

Apex code is used to write custom and robust business logic. As with any language,
there are key coding principles and best practices that will help you write efficient,
scalable code. Check our Apex best practices of Salesforce.

1. Bulkify Apex Code

2. Avoid SOQL & DML inside for Loop


3. Querying Large Data Sets

4. Use of Map of Sobject

5. Use of the Limits Apex Methods

6. Avoid Hardcoding IDs

7. Use Database Methods while doing DML operation

8. Exception Handling in Apex Code

9. Write One Trigger per Object per event

10. Use Asynchronous Apex

18. What is Apex Trigger? and When we should use Apex Trigger?

The trigger is a procedure in a database that automatically invokes whenever a special


event in the Database occurs. Apex triggers enable you to perform custom actions
before or after events to records in Salesforce, such as insertions, updates, or
deletions. Learn more about apex trigger here.

There lots of automation tool available in Salesforce. Lets understand the when to use
Apex Trigger in Salesforce.

1. Complex logic incapable of being processed via declarative artifacts

2. Logic associated with DML

3. Operations on unrelated objects

4. Integration with External Systems

19. What is Apex Trigger Handler pattern?

Check this blog post to learn about which all trigger patterns are available in Salesforce.
For Trigger Handler code check this post.
20. What is Apex Trigger Framework? What are different Trigger Framework are
available in Salesforce?

How many trigger frameworks are available in Salesforce, which one is a lightweight
apex trigger framework and a Comparison of different approaches? Check our Apex
hours Trigger Framework in Salesforce sessions.

Type of different frameworks in Salesforce

1. Trigger Handler Pattern

2. Trigger Framework using a Virtual Class

3. Trigger Framework using an Interface

4. An architecture framework to handle triggers

21. What is Async Apex in Salesforce? How many ways do we have for Async
processing?

In technology terminology, Asynchronous operation means that a process operating


independently of other processes.

Using Async in Salesforce – how will we do it?

1. Schedule & Batch jobs

2. Queues

3. @future

4. Change Data Capture – Apex Triggers (Summer ’19)

5. Platform Events – Event Based

6. Continuations (UI)

22. What is a Batch job in Salesforce?

Batch class is used to process millions of records with in normal processing limits. With
Batch Apex, we can process records asynchronously to stay within platform limits. If
you have a lot of records to process, for example, data cleansing or archiving, Batch
Apex is probably your best solution. In Batch Apex each transaction starts with a new
set of governor limits, making it easier to ensure that your code stays within the
governor execution limits

23. What is the difference between the Stateful and Stateless batch jobs?

Using Stateful Batch Apex


If your batch process needs information that is shared across transactions, one
approach is to make the Batch Apex class itself stateful by implementing
the Stateful interface. This instructs Force.com to preserve the values of your static and
instance variables between transactions.

global class SummarizeAccountTotal implements Database.Batchable<sObject>,


Database.Stateful{

In Short, if you need to send a mail to check the number of records passed and failed in
the batch job counter, in that case, can you Stateful batch job?
If you want to create one counter and share/ use it in each execute method use the
same.

Using Stateless Batch Apex

Batch Apex is stateless by default. That means for each execution of


your execute method, you receive a fresh copy of your object. All fields of the class are
initialized, static and instance.

global class SummarizeAccountTotal implements Database.Batchable<sObject>{

24. What is mixed DML?

A Mixed DML operation error occurs when you try to persist in the same transaction
and change to a Setup Object and a non-Setup Object. For example, if you try to
update an Account record and a User record at the same time.

Salesforce Developer Lightning Interview Question and Answers

25. What is Lightning Data Service?

Use Lightning Data Service to load, create, edit, or delete a record in your component
without requiring Apex code. Lightning Data Service handles sharing rules and field-
level security for you. In addition to simplifying access to Salesforce data, Lightning
Data Service improves performance and user interface consistency

26. How to do communication between Lightning web components?

Use the Events in lightning web components (LWC) to communicate between


components. Events in Lightning web components are built on DOM Events, a
collection of APIs and objects available in every browser. Here we will be see how to the
events using the Custom-event interface and publish-subscribe utility.
Learn about Event in LWC in our Events in Lightning web components post. Events are
used in LWC for components communication. There are typically 3 approaches for
communication between the components using events.

1. Parent to Child Event communication in Lightning web component

2. Custom Event Communication in Lightning Web Component (Child to Parent )

3. Publish Subscriber model in Lightning Web Component or LMS (Two


components which doesn’t have a direct relation )

27. How to call Apex class in Lightning web component and how many way we have
and when to use which option?

You can call the apex methods as functions into the component by calling either via the
wire service or imperatively. To call an Apex method, a Lightning web component can:

• Wire a property

• Wire a function

• Call a method imperatively

To expose an Apex method to a Lightning web component, the method must be static
and either global or public. Annotate the method with @AuraEnabled

Learn more from the Call apex method from the Lightning web components post.

28. What are the basic difference between Application Event and Component Event
in Aura component?

Application Event Component Events

Application Events are handled by any component have Component Events can be handled b
handler defined for event.These events are essentially a component or a component that inst
traditional publish-subscribe model contains the component

The component events can only be re


Application event can be used through out the application.
component and handled by parent c

We use attribute type="APPLICATION" in the aura:event tag for We use attribute type="COMPONEN
an application event. the aura:event tag for a component e

29. What is a lightning messaging service?

Lightning Message Service (LMS) allows you to communicate between Visualforce and
Lightning Components (Aura and LWC both) on any Lightning page. LMS API allow you to
publish message throughout the lightning experience and subscribe to the same
message anywhere on lightning page.

Learn more here.

30. What is lazy loading in LWC and how do lazy loading in LWC?

Lazy loading is an optimization technique to load the content on demand. Instead of


loading the entire data and rendering it to the user in one go as in bulk loading, the
concept of lazy loading assists in loading only the required section and delays the
remaining, until it is needed by the user.

Learn how to use lazy load in the lightning web component here.

31. What are Design Attributes in Lightning Web Components?

We can use Design Attribute to make lightning web components attribute available to
System Admin to edit Lightning App Builder or Community. So we can expose the
component attribute in Lightning App Builder using design Attribute.

Learn more from Design attributes in Lightning Web Components post.

Salesforce Integration Interview Questions

Here is a list of the most frequently asked Salesforce Integration question in the
Developer Interview.

32. What is web services?

Web service is a standardized medium to propagate communication between the client


and server applications on the World Wide Web. Web services provide a common
platform that allows multiple applications built on various programming languages to
have the ability to communicate with each other.

Webservices is a functionality or code which helps to us to do integration. Web services


are open standard (XML, SOAP, HTTP, etc.) based web applications that interact with
other web applications for the purpose of exchanging data

33. What is the difference between SOAP and REST?

Here is the difference between SOAP and REST API.

SOAP API REST API

Relies on SOAP protocol Relies on REST architecture using

Transports data in XML Transports data in JSON or XML


Highly structured/ typed Less structured? Less bulky data

Handles large data loads Works well with JavaScript

Designed with large enterprise application in mind Designed with mobile devices in m

34. What is the difference between Enterprise WSDL and Partner WSDL?

Here is the difference between Enterprise WDSL and Partner WDSL.

Enterprise WDSL Partner WSDL

Strongly Typed Loosely Typed

Tied to a specific configuration of Salesforce Useful for any configuration of Salesforce

Changes if custom field or custom objects are Does not changes if custom field or custom object
added to your organization organization’ Salesforce configuration

35. Explain about Integration Patterns?

In Salesforce, we have welcome Integration patterns.

1. ” Remote Process Invocation—Request and Reply ”: Salesforce invokes a


process on a remote system, waits for completion of that process, and then
tracks state based on the response from the remote system.

2. ” Remote Process Invocation—Fire and Forget ”: Salesforce invokes a process in


a remote system but doesn’t wait for completion of the process. Instead, the
remote process receives and acknowledges the request and then hands off
control back to Salesforce.

3. ”Batch Data Synchronization”: Data stored in Lightning Platform is created or


refreshed to reflect updates from an external system, and when changes from
Lightning Platform are sent to an external system. Updates in either direction are
done in a batch manner.

4. ”Remote Call-In ”: Data stored in Lightning Platform is created, retrieved,


updated, or deleted by a remote system.

5. ” UI Update Based on Data Changes ”: The Salesforce user interface must be


automatically updated as a result of changes to Salesforce data.
6. “Data Virtualization ”: Salesforce accesses external data in real time. This
removes the need to persist data in Salesforce and then reconcile the data
between Salesforce and the external system.

Question 1. What are the different types of relationships we have in Salesforce?

Answer – In Salesforce we have 6 different types of relationships:

1. Lookup – It is a loosely coupled relationship between two objects. Where


objects can be connected as Many to One or One to Many.

2. Master Detail – It is a tightly coupled relationship between two objects. It also


can be Many to one and One to many. tightly coupled means the Child record
cannot exist without the Parent and If we delete the Parent then the child also
gets deleted.

3. Many-Many – It is a type of relationship where an object can have multiple


children of another object and vice versa. Suppose we have obj A and obj B So
now A can have multiple B records associated with and B can also have multiple
A’s associated with it. To establish this kind of relationship we took a junction
object which acts as a child for both objects A and B.

4. Self – It is a relationship where obj is connected to itself. For example, we have


an Account object which has a self-lookup. Where an account can act as a
Parent record and can have child accounts associated with it.

5. External – This relationship is implemented through the use of lookup where an


external object is related to a Salesforce object.

6. Hierarchal – It is a unique relationship in salesforce which applies to the User


object. It displays the parent-child relationship within a single object. It basically
enables users to select another user as their manager.

Question 2. How can we handle record-level security?

Answer – In Salesforce we can handle record-level security in the following different


ways:

1. OWD – It’s the baseline level of security. Here we define the default level of
access that a user gets on records they don’t own. We have a different option
which defines which level of access would be given: Private, Public Read-Only,
Public Read/Write, Public Read/Write/Transfer.

2. Role hierarchy – In this option user gets access to the record owned by other
users in roles below them. As this option is used to open up the security given by
OWD it extends the access when the Sharing Setting is set to not more restrictive
than Public Read/Write. So if OWD is set to Public Read/Write so there is no need
to give access from Role Hierarchy.

3. Sharing Rules – They are used to give access to records to the user based on
ownership or some criteria. It opens up access compared to Role Hierarchy. So
while creating we have two options: Based on the record owner and Based on
criteria. For example: if we have to provide access to some user if Opportunity
moves to Closed Won then we can achieve this scenario by use of Sharing Rules.

4. Manual Sharing – We use this when we want to share access to individual


records with some users, groups, etc. To provide access we can just simply go to
the record we want to share and click on the Sharing option available on the
Record Page then Select whom we want to share and what access we want to
provide.

Question 3. Suppose I have a scenario where I have one master detail relationship
between A(master) and B object. Currently, the OWD of A is public read-only and
now I have changed the relationship to lookup. What will be the OWD now of B
object?

Answer – In the master-detail relationship, the child sharing setting will be controlled by
a parent but when we update the data type to lookup, the child object (B) OWD will be
updated to Public Read/Write.

Question 4. How can we call Apex in Flow?


Answer – If we want to call out Apex in flow then we have to use Invocable method
annotation in our apex class. Basically, by annotating with this, we are making our class
accessible to the salesforce declarative tools.

Below is the syntax:

public class DemoClass {

@InvocableMethod(label='Test' description='Test' category='Test')

public static void demoMethod() { }}

Question 5. What are the different types of trigger and context variables we have in
Salesforce?

Answer – In Salesforce we have two types of triggers which are before and after which
define whether the trigger executes before or after the record gets saved to the
database. Following are the different types of context variables we have in Trigger:

1. isInsert

2. isUpdate

3. isDelete

4. isBefore

5. isAfter

6. New

7. Old

8. oldMap

9. newMap

10. isExecuting

11. isUndelete

12. operationType

13. size

Question 6. What is recursion in Trigger and how can we prevent it?

Answer – Recursion occurs when the trigger invokes itself in a loop and eventually hits
the governor’s limit due to repeated execution and iteration. We can also encounter the
error “Maximum trigger depth exceeded” due to multiple executions because the stack
depth limit in Salesforce is 16.
For Example: If a trigger is firing on an Account’s update and in that trigger logic we are
updating those Accounts then it will lead to recursion due to multiple executions.

Avoiding recursion is very important in Salesforce to ensure stability and efficiency. We


have different methods to avoid recursion in trigger

Following are the ways by which we can prevent recursion in trigger:

1. Static Boolean variable – We will use the boolean variable make it default true,
and check the value if true, will enter it into the transaction and make it false
afterwards.

2. Static Set – In this process we will store the processed ID and check if the ID is
contained in the Set or not.

3. Static Map – Here, we will create a Map of String and Set of Id (Map<String,
Set<Id>>) to store the processed Id with their event.

4. Static Old Map – We will use the old map to compare the values before
executing.

Question 7. Write a trigger to calculate the total contact that the Account has and
also include all applicable context variables.

Answer – To achieve this scenario we have two ways. Firstly we create our trigger on
Contact as shown below

ContactTrigger.apxt

trigger ContactTrigger on Contact (after update, before update, after insert, before
insert, after delete, before delete, after undelete) {

if(Trigger.isAfter) {

if(Trigger.isInsert || Trigger.isUpdate || Trigger.isDelete || Trigger.isUndelete) {

ContactTriggerHandler.updateContactCount(Trigger.newMap, Trigger.oldMap);

}}}

Here we are using After because we are performing operation on a related object. This
scenario will be applicable to Insert, Update, Delete and Undelete. It is better to have
trigger logic less which means it is a best practice to write any logic in the trigger so
that’s why we have used a helper class here as “ContactTriggerHandler”. Below is the
code for this helper.
ContactTriggerHandler.apxc

public class ContactTriggerHandler {

public static void updateContactCount(Map<Id,Contact> newMapContactById,


Map<Id,Contact> oldMapContactById) {

Set<Id>accountIds = new Set<Id>();

List<Account>accountsToUpdate = new List<Account>();

if(newMapContactById != null) {

for(Contact con: newMapContactById.values()) {

if(con.AccountId != null) {

if(oldMapContactById != null && oldMapContactById.size() > 0) {

Contact oldContact = oldMapContactById.get(con.Id);

if(oldContact.AccountId != con.AccountId) {

accountIds.add(oldContact.AccountId);

}}

accountIds.add(con.AccountId);

}}}

if(oldMapContactById != null) {

for(Contact con: oldMapContactById.values()) {

accountIds.add(con.AccountId);

}}

List<AggregateResult> aggList = [SELECT Count(Id) countId, AccountId FROM Contact

WHERE AccountId IN : accountIds GROUP By AccountId ];

for(AggregateResult agg : aggList) {

Account acc = new Account();

acc.Id = (Id)agg.get('AccountId');

acc.No_of_Contact__c = (Double)agg.get('countId');

accountsToUpdate.add(acc);
}

try {

if(accountsToUpdate != null && accountsToUpdate.size() > 0) {

update accountsToUpdate;

}}

catch(Exception e) {

System.debug('Error occured while updating Account '+ e.getMessage());

}}}

Above the is code to update the Account with the number of contacts. Here we have
created the custom field to update the count No_of_Contact__c. We have utilised
Aggregate SOQL here to calculate the count.

Below is another way of updating the Contact count in the Account without using
Aggregate SOQL.

for(Account acc : [SELECT Id,No_of_Contact__c, (SELECT Id FROM Contacts) FROM


Account WHERE Id IN : accountIds]) {

acc.No_of_Contact__c = acc.contacts.size();

accountsToUpdate.add(acc);

Question 8. Suppose I have a scenario where I want to restrict the user from
updating the Account record multiple times if the record is already updated within
that 1 hour. Write a trigger for this scenario

Answer – Here we have to apply validation to restrict users to update accounts within
the same hour. So we will be using before type here.

AccountTrigger.apxt

trigger AccountTrigger on Account (after update, before update, after insert, before
insert, after delete, before delete, after undelete) {

if(Trigger.isBefore && Trigger.isUpdate)

AccountTriggerHandler.restrictAccountUpdate(Trigger.oldMap, Trigger.newMap); }
AccountTriggerHandler.apxc

public class AccountTriggerHandler {

public static void restrictAccountUpdate(Map<Id,Account>oldAccountMap,


Map<Id,Account>newAccountMap) {

if(newAccountMap != null) {

for(Account acc: newAccountMap.values()) {

if(oldAccountMap != null) {

Account oldRecords = oldAccountMap.get(acc.Id);

if(oldRecords.LastModifiedDate.addHours(1) > System.now()) {

acc.addError('You cannot update account within 1 hours');

}}}}}}

OUTPUT

Question 9. What is with sharing and without sharing in Apex?

Answer – We can use this in class to determine whether sharing rules should be
enforced or not.
With Sharing – When we want to run our apex class in respective of the Sharing rules of
the current user then we use it. Below is the syntax of how we can apply it.

public with sharing class demoClass { // Code here }

Without Sharing – When we don’t want to run our apex class in respective of the
Sharing rules of the current user’s then we use it. Below is the syntax of how we can
apply it. It is a best practice to always use the class in with sharing until and unless
there is a specific requirement to use without sharing.

public without sharing class demoClass { // Code here }

Also, it only applies to share and does not enforce the field and object level security. If
we want to enforce those we have to explicitly apply it. For example: If the user does not
have access to obj A so even though the class is running without sharing user will not
get access to obj A.

Question 10. In continuation of the above question, does the apex trigger run with
sharing or without sharing?

Answer – Apex triggers can’t have an explicit sharing declaration and run as without
sharing.

Question 11. I have two Apex classes A and B. A is OuterClass which is called B so
that will be an InnerClass. A is running in with sharing context and B is running
without sharing context. Now B has a method inside it, So in which context will that
method be running?

Answer – Class B’s method will run without sharing context and will not depend on the
outer class. Inner classes do not inherit the sharing setting from their container class.

Question 12. What is row cause in sharing?

Answer – Row cause in sharing in Salesforce used in Apex sharing. It basically stores
the reason why a particular record is being shared with a user or a group.

Question 13. Write an SOQL to fetch all Accounts which is not associated with any
contacts

Answer – To execute this SOQL we will use the NOT operator in SOQL. Below is the
SOQL we used. Here we have used NOT IN and then we have also used another query
which basically gives the AccountId from Contact. So it will filter out the Account whose
ID is not there in any contacts.
1

SELECT Id, Name FROM Account WHERE Id NOT IN (SELECT AccountId FROM Contact)

Question 14. I have a scenario where I want to fetch the Account with second
second-highest Annual Revenue.

Answer – To implement this scenario we can OFFSET and LIMIT available in SOQL.
OFFSET basically removes the n record from the list. LIMIT gives us only n record.

So to show you I have also executed another SOQL which is ordered by Annual Revenue
in Descending order and we can see “Express Logistics and Transport” coming as the
second highest.
Now to just fetch the second highest only we can use the below SOQL.

SELECT Id, Name, AnnualRevenue FROM Account WHERE AnnualRevenue != null


ORDER BY AnnualRevenue DESC LIMIT 1 OFFSET 1

Below is the output:

Question 15. How can we enable field security while implementing our SOQL?

Answer – To apply field-level security we can use WITH USER_MODE or


WITH SYSTEM_MODE. In User mode, the security will be respected of that current user
but with System mode, it will not apply the user’s security and will run in the System
context. Below is the sample code of how can we implement it.

List<Account> acc = [SELECT Id FROM Account WITH USER_MODE];

Question 16. Business Scenario

I have a field called Rating on Account which is having 3 picklist values: Hot, Warm, and
Cold. I want to write a SOQL query to fetch the counts of each value. Like I want to know
how many records have a Rating Hot value in the Rating field and so on for each value.

Answer – Here we can use the aggregate SOQL like below.

SELECT Count(Id), Rating FROM Account WHERE Rating != null GROUP BY Rating
Question 17. How can we fetch the current user’s ID in LWC without using Apex?

Answer – To fetch the current user’s ID in LWC we can use the salesforce module and
we can import the ID from it. Below is the sample JS

import { LightningElement } from 'lwc';

import Id from '@salesforce/user/Id';

export default class GetUserIdComp extends LightningElement { userId = Id; }

Question 18. Suppose we have a field on Account as Active of type picklist and has
2 values: Yes, No. While creating the value we can provide any value amongst this
picklist but once we update it to Yes, It can’t be moved to No. How can we
implement this scenario?

Answer – To implement this scenario we make use of the before update trigger. Below is
the helper class logic we can use

public class AccountTriggerHandler {

public static void restrictAccountUpdate(Map<Id,Account>oldAccountMap,


Map<Id,Account>newAccountMap) {

for (Account acc : newAccountMap.values()) {

Account oldAcc = oldAccountMap.get(acc.Id);


if (oldAcc.Active__c == 'Yes' && acc.Active__c != 'Yes') {

acc.addError('Account cannot be deactivated once active);}

}}}

Question 19. Business Scenario

Suppose I have a sharing rule by which User A is getting access to certain records as
that user is part of a certain group which is mentioned in the sharing rule. Now I want to
limit access to a few records that have matching criteria from User A. How can I
implement this scenario?

Answer – To implement this scenario we can make use of Restriction Rules. These are
available on custom objects, external objects, contracts, events, tasks, time sheets,
and timesheet entries. They basically apply a filter to the records shared via OWD or
another share mechanism. We can have up to 2 restriction rules per object.
Question 20. What is mixed DML error and when do we encounter it??

Answer – We encounter this error whenever we are performing DML operations on the
Setup and Non-Setup objects in a single transaction due to which sharing is getting
recalculated then only we face this error. Let’s take a look at the below code to
understand it clearly.

public static void mixedDMLDemo() {

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

insert a;

Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];

UserRole r = [SELECT Id FROM UserRole WHERE Name='CEO'];

User usr = new User(alias = 'testGeek', email='test@geek.com',

emailencodingkey='UTF-8', lastname='Geek',

languagelocalekey='en_US',

localesidkey='en_US', profileid = p.Id, userroleid = r.Id,

timezonesidkey='America/Los_Angeles',

username='test@geek.com');

insert usr; }

Here, we are inserting Account and User both in a single transaction and we are
assigning user-role to that user due to which sharing is calculated as a result mixed DML
will be introduced.
Question 21. What are the ways to avoid mixed DML errors?

Answer – To avoid this error we need to convert this process from synchronous to
asynchronous. The possible way is to make it a Future Method. It will separate the
transaction which help us to avoid this error.

Question 22. What is the default and maximum size of the batch?

Answer – The default is 200 and the maximum size is 2000.

Question 23. Can we call the future from the batch?

Answer – No, we cannot call future methods from batch apex. As they operate
differently. Mixing these can lead to unexpected behaviour.

Question 24. Business Scenario

Suppose I am running a batch to update the object record. Now client wants when the
batch finishes running, they should get the mail with the count of how many records
updated successfully and how many have failed. How can we implement this scenario

Answer – We can implement this scenario by using a Database.Stateful interface. By


using this our instance variable will maintain the state across multiple batches.
Normally, when a batch job runs (without implementing Database.Stateful ) the
instance variable gets reset between batch executions. Below is the code to implement

global class MyBatchClass implements


Database.Batchable<sObject>,Database.Stateful {

// Define variables to store success and failure counts

// to store the count of success records

global Integer successCount = 0;

// to store the count of failure records

global Integer failureCount = 0;

global Database.QueryLocator start(Database.BatchableContext bc) {

return Database.getQueryLocator([SELECT Id, Name FROM Object__c]);

global void execute(Database.BatchableContext bc, List<sObject> scope) {

// Perform callouts and process records

for (Object__c obj: scope) {

//execute logic
try {

// Increment success count

successCount++;

} catch (Exception e) {

// Handle records failure

failureCount++;

}}}

global void finish(Database.BatchableContext bc) {

// Send email with success and failure counts

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

String[] toAddresses = new String[] {'user@example.com'};

mail.setToAddresses(toAddresses);

mail.setSubject('Batch Job Completion Report');

mail.setPlainTextBody('The batch job has completed.\n\nTotal Success Count: ' +


successCount + '\nTotal Failure Count: ' + failureCount);

// Send email

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

}}

Question 25. Business Scenario

I have an LWC component that takes multiple inputs from the user for the Account
record and has a button which when the user clicks it, calls the apex method which
handles the update. But while clicking the button user is facing below Limit Exception
below. What could be the possible reason?

Below is the LWC and Apex running behind


Answer – Here in the code we can see that we are calling our apex method imperatively
but we use the cacheable = true in the annotation with @AuraEnabled. So we have to
use only @AuraEnabled with the imperative call because it doesn’t use the browser
cache and by default @AuraEnabled executes with cacheable=false.

At the time of using it with wire, we have to explicitly make it true because wire uses
browser cache.

Question 26. How can we able to communicate between two LWC components?

Answer – For communication in LWC we have different ways: Parent to Child, Child to
Parent, Lightning Message Service.

1. Parent to child – To establish this type of communication we use @api decorator


in LWC as it can expose that variable public which helps us to communicate with
another component.

2. Child to Parent – To implement this we dispatch the event from the child and
catch it in the parent.
3. Lightning Message Service – Here we create the Channel and one component
will be the publisher from which we want to send the data and one will be the
subscriber who receives the data.

Question 27. Business Scenario

Suppose I have a batch running and in the start, it fetches around 1000 records of
accounts and the batch is running in 5 so each batch will take 200 records with it. In the
execute method I have a loop running over that list of accounts. I am updating the
account record in the loop. Now what could be the possible governor limit I can hit?

Below is the code for the batch:

Answer – Here the possible limit I can hit is LimitException because we are updating in
the loop and when the scope is getting 200 records. The DML limit per transaction for
Batch is 150 so as soon as I get the 151th record in the loop I’ll get the error.

Question 28. What is event bubbling and event capturing in LWC?


Answer – Event bubbling and capturing are basically the concepts of JavaScript. In
Event bubbling child component propagates up through the Parent component which is
the default behaviour we can see in the LWC while we implement child-to-parent.

Event capturing is the opposite of Bubbling, here component will propagate downward
to the child from the Parent. It is not the default behaviour we have to explicitly make it
true.

Suppose we have 3 components childComp, parentComp, and grandParentComp and


we want to communicate from child to grandparent then while dispatching the event we
can set the bubble and composed property as true so that the event can move up to a
higher hierarchy And can easily cross the Shadow boundary.

Question 29. What are deep copy and shallow copy of objects?

Answer – Shallow copy creates the copy of an object but not for its nested properties. It
creates a reference to it. So any changes to the nested properties of a copied object will
also change to the original one. Like spread operator creates the shallow copy.

Hence you can see above the copied object and the original both get changed for the
nested object.
But for a deep copy, it is different, it creates the copy without actually referencing them
so any changes in the copied object will not affect the original one and by
JSON.stringify(JSON.parse(obj1)) we can create the deep copy of objects.

Question 30. Business Scenario

Let’s say I have a batch with a total of 1000 records to execute, and the batch size is set
to 200. This means that the processing will occur in 5 batches. If the first 4 batches are
processed successfully but encounter an error in the 5th batch due to 4-5 records, the
question is whether the entire batch is rolled back or only those 4-5 problematic
records are rolled back.

Answer – In this scenario, that entire batch is rolled back.

Question 31. What is the limit of total number of records retrieved by SOQL
queries?

Answer – The limit of the total number of records retrieved by SOQL queries in
Salesforce is 50,000 for both synchronous and asynchronous.

Question 32. What are the CPU time limit and Execution time limit in Salesforce?
Answer – In Salesforce CPU Time is calculated based on all the executions on the
Salesforce application servers occurring in one Apex transaction—for the executing
Apex code, and any processes that are called from this code, such as package code and
workflows. Time spent in DML, SOQL and SOSL isn’t counted.

So synchronously we have 10 seconds and in asynchronous we have 60 seconds.

Execution time for each Apex transaction we have is 10 minutes for both Synchronous
and Asynchronous.

1. What are governor limits? Please provide some examples.

Governor limits are resource utilization limits enforced on Apex by Salesforce to prevent
run away processes from monopolizing resources. This is vital as Salesforce is a multi-
tenanted environment, so run resources are shared. Examples of these are the number
of SOQL queries, DML statements, and the number HTTP callout requests in a
transaction.

2. What programming languages can we use to customise a Salesforce instance?

The server side language used to customize Salesforce is called Apex, which has a
syntax similar to Java. On the front end, we have several technologies, the main one
being Lightning Web Components, followed by the older and now more niche Aura
Components and Visualforce – all of which use HTML, CSS, and JavaScript in
conjunction with Apex. We can also use Flow, which is a low code language to
customize both the front end and the backend.

3. What declarative tools can we use to customize a Salesforce instance?

The most basic declarative tool is custom fields and custom objects, which can be
defined declaratively and allow us to customize an instance’s database schema. We
can further customize objects through the use of page layouts, and Lightning app pages
to declaratively customize the look and feel of a record’s page.

If we wish to create declarative automations, we should be using Flow, while Process


Builder and Workflow Rules exist, these are being deprecated by Salesforce and so
declarative automations should be created via Flow instead.

4. When would we choose programmatic development over declarative?


Declarative tools excel when rapid development is required as, due to their nature, they
allow rapid iteration and usually have shorter build times. In scenarios where the
business logic required is relatively straightforward, with very few “gotchas”, it usually
makes sense to take advantage of declarative tools with faster build time, which can
translate to a cheaper build.

We would choose programmatic development when the requirements become more


complex, such as in very specialized business processes which don’t lend themselves
to Flows, etc. Other scenarios are where performance or user interface is of paramount
importance.

One of the main advantages of running a coded solution is that performance will exceed
that of a declarative solution due to the ability to use more specialized logic and
removing overheads. This also applies to user interfaces as using a coded solution
allows us to fully customize it to our requirements, whereas using declarative tools
means we are stuck with what comes out-of-the-box – which may not provide the
desired outcome.

5. What is the Salesforce release model?

Salesforce has major updates three times a year, seasonally, in Spring, Summer and
Winter. The specific dates for these vary, however, around 4-6 weeks before a release,
sandbox instances are updated to allow for testing of any customizations in an org.

6. What Salesforce supported development tools are there?

The main Salesforce supported development tool is the Salesforce Extensions for VS
Code which utilizes the Salesforce Command Line Interface.

7. What are three types of object relationship?

Lookup Relationship: Two records related to each other through one object (the child)
having a lookup field which is pointing to the other (the parent).

Master-detail: Similar to a lookup relationship, however in this case the child record is
considered the detail and the parent the master. This type of relationship changes some
behaviours of the detail records, such as having sharing controlled by the master and
allowing special rollup-summary fields to be created on the master.

Self: A lookup relationship which points to the same object type, allowing a hierarchy or
chaining of records of the same type. However, a record cannot be related to itself.
8. What is SOQL?

SOQL stands for Salesforce Object Query Language, and as the name suggests it is the
main language used for performing queries against the database. While it has a similar
syntax to SQL, there are a few key differences, mainly that SOQL is exclusively used for
queries (i.e. SELECT statements).

It is used to retrieve data from a single object, and potentially those directly related to it.
SOQL can be used both within Apex code – to query records for consumption by said
code – or via the API and tools which use it – such as in data loading tools.

Apex Programming

9. What is required for deploying Apex code to a Production instance?

When deploying Apex code to production, there are three things which are required:

1. All classes and triggers must successfully compile.

2. Tests must cover at least 75% of all Apex code and there must not be any
failures.

3. All triggers must have at least 1% coverage.

10. What’s the difference between queueable Apex, batch Apex and schedulable
Apex?

All three are different ways of running asynchronous Apex code:

Queueable Apex: This is an async process which can be launched to run processing,
callouts, etc. This is useful when trying to do processes in triggers which are long
running, or simply unavailable, e.g. callouts.
Batch Apex: An Apex process which is designed to handle large numbers of records (up
to 50 million) by processing them in smaller batches of 1 – 2000 records at a time.

Scheduled Apex: A process that is scheduled to run at a specific time and date. This
can be customized to be repeatable, either by scheduling it through the UI, or via a
CRON string within other Apex code.
11. What are the different events for an Apex Trigger?

Triggers are split into two main types: before and after.

Before triggers run before a record has been saved into the database – optimally used
for same record calculations and validations. Whereas, after triggers run after the
record has been saved, and should ideally be used for working on records other than
the one invoking the trigger.

Triggers are then further broken down into the type of operation which invokes it. These
are: insert, update, delete, and undelete. This allows the triggers to be customized to
only be invoked when explicitly required.

12. What is a global Apex class?

A global Apex class is an Apex class which has been declared with the global access
modifier. This means that the class is visible and usable by any Apex code running in any
namespace. Global Apex class should rarely be used and only implemented when
explicitly necessary, e.g. within managed packages or for Apex REST web services.

13. What is an Interface and why would we use one?

An interface is similar to a class, except none of its methods have an implementation.


This is useful for abstracting method declaration from its specific implementation. A
common example of this can be found with Batch classes, which implement the
standard Salesforce interface of Database.Batchable.

Using interfaces signifies that a class will explicitly implement the methods defined in it,
potentially allowing us to implement different behavior at run time based on context.

14. How can we allow Apex to be called by Lightning components?

To call Apex code from a Lightning Component, it first must be annotated


with @AuraEnabled. This exposes the code to be called from within the components
JavaScript. We can adjust the annotation a little further to indicate that the method
supports caching by using the @AuraEnabled(cacheable=true) annotation instead.
15. How can we debug our Apex code?

When Apex code runs, we can generate debug logs for the executed code. These logs
provide an insight into what happened during execution, any exceptions that were
thrown, and also provide the details of anything passed into a System.debug() method
call.

If we increase the logging levels sufficiently, we can also use the Apex Replay Debugger,
which allows us to use VS Code to step through the code execution and examine it in
more detail and set checkpoints and breakpoints for a more in-depth debugging
experience.

Integrations

16. How can we integrate into external REST web services?

For integrating with external REST web services, we would tend to use HTTP callouts to
invoke the external API. We can use the JSON and XMLStreamWriter classes to build
payloads to match the specifics of the external API.

17. How can an external system integrate into Salesforce?

External systems can utilize the built in REST API provided by Salesforce for simple
integrations. This could be for creating, updating, querying records. For more niche, or
bespoke, inbound integrations.

18. How can we secure credentials used for outbound integrations?

Depending on the type of credentials, we have a few options. The most preferred
is Named Credentials which specify the base endpoint and the authentication
credentials. These are preferred since Salesforce then handles the authentication for us
and keeps the credentials away from prying eyes.

Alternatively, if named credentials are not suitable, we could choose to store the
credentials in a Custom Metadata type, which will allow different credentials to be
used across different environments and we can secure the permissions to access the
metadata type. We should never be hard coding the credentials for integrations within
our code as this is very insecure.

Lightning Components

19. What is the difference between Lightning Web Components and Aura
components?

Lightning Web Components is built using current web standards to build custom HTML
elements, through the use of Web Components – designed to run in a lightweight and
performant manner. Aura components are the legacy Lightning Component framework,
but still utilize JavaScript and HTML for development.

20. Why would we use Lightning Web Components over Aura components and vice
versa?

Ideally, we should always be using Lightning Web Components for any new
developments, due to their easier development and better performance. We should
avoid using Aura components unless we wish to use a piece of functionality which is not
yet supported in LWCs, in this case we should wrap an LWC inside of an Aura
component.

Read more:

• Migrate Aura Components to Lightning Web Components

• Lightning Web Components and Aura Components Working Together

21. How can Lightning Web Components be made configurable by an Admin?

We can define our configurable properties in a components .js-meta.xml file. This is


done by defining a property tag within the targetConfig tag for our specific target and can
further be extended to only apply to specific objects, or to limit the objects which the
component can be placed on.
22. Where can we use Lightning Components?

Lightning components can be deployed in a large number of places across an org.


These can be admin decided ones or added by developers. These include:

• The Utility Bar

• Outlook and Gmail integrations

• Flows

• Visualforce pages

• External web pages

• Pre-chat snap-ins

• Quick Actions

23. What is SLDS?

The Salesforce Lightning Design System (SLDS) is the user interface design framework
used by Salesforce for designing, styling, and building all aspects of Salesforce
Lightning.

As developers, we can utilize the SLDS provided CSS styles or component markup
templates to build custom components which provide a consistent UI with the rest of
the platform. SLDS also provides guidelines around accessibility, language guidance,
and icons.
Secure Development

24. How can we enforce Field Level Security (FLS) within our Apex code?

There are a few approaches depending on the context of where we wish to enforce Field
Level Security.

If we are performing a query, and do not require graceful handling of missing


permissions, we can add the WITH SECURITY_ENFORCED clause to the query. This will
cause an insufficient permissions exception to be thrown if any permissions to the
requested fields are missing.

If we need more granularity or wish to simply remove fields a user does not have
sufficient permissions for, we can use the Security.stripInaccessible() method. As the
name suggests this method checks for, and removes any field values for, the specific
context requested, e.g. removing fields which the user does not have permissions to
update.

25. How can we enforce Sharing Rules within our Apex code?

We can define our class to use the with sharing keywords in its definition. Alternatively
we can use the inherited sharing keywords, which inherits the sharing modifier from its
calling class for when we need code that should handle this dynamically.
26. When should we bypass sharing and FLS within our code?

We should only bypass these when we are running system level processes. If we do
need to bypass them for user operations, we should be ensuring there is no chance data
or actions which are unintended can be performed.

This could be by migrating the specific actions which require bypassing to separate
classes and performing the rest of our logic with sharing and FLS enforced. We should
only ever be bypassing it for specific actions, not an entire set of business logic.

27. How can we secure dynamic SOQL?

When we are performing dynamic SOQL which takes an input from a user, we must
sanitize the user input. We do this by making sure all single quotes are escaped before
performing the query. Alternatively, wherever possible, we want to use bind variables,
even with our dynamic SOQL.

Configurable Development

28. What is a roll-up summary field?

Roll-up summary fields are special fields which lie on the master side of a master-detail
relationship. These fields have their values calculated based on an aggregate of the
detail side of the relationship – this could be anything from the number of records to a
field value summed up. It allows us to skip using Apex when we wish to aggregate
record values that are part of a master-detail relationship.

29. What are Custom Metadata Types and why would we use them?

Custom Metadata Types are developer designed pieces of metadata which facilitate the
designing and building of customizable applications within a Salesforce instance. This
is done by first designing the metadata type, which is similar to a custom object, and
then by creating records of that type to define the required behavior, by being read at run
time. This could be anything from defining a field mappings table between two objects,
to storing secrets for an API integration.

30. What is dynamic Apex?


Dynamic Apex is a technique in which we make our code more flexible by accessing
sObjects and fields dynamically, rather than declaratively, within our code. This is
mainly done through the use of sObject tokens and describes to dynamically access
and set sObject field values within our code. This can be used in conjunction
with dynamic SOQL to dynamically build queries based on runtime context, rather than
design time.

Interview Questions and Answers for a Junior Salesforce Developer

1. Can you explain what Salesforce is and why it is used?

Answer: Salesforce is a cloud-based CRM platform. It helps businesses manage


customer information, streamline processes, and improve customer relationships. It’s
used for its versatility, scalability, and extensive feature set.

2. What are some common Salesforce products you are familiar with?

Answer: I am familiar with Sales Cloud, Service Cloud, Marketing Cloud, and Salesforce
Commerce Cloud. Each serves different aspects of CRM, from sales and customer
service to marketing and e-commerce.

3. Can you describe what Apex is and its uses?

Answer: Apex is a proprietary programming language by Salesforce. It’s used for writing
server-side logic and custom business processes in the Salesforce environment.

4. How would you handle data migration in Salesforce?

Answer: Data migration in Salesforce involves planning, mapping data fields to


Salesforce fields, using data loader tools, and testing. It’s crucial to ensure data
integrity and security during this process.

5. Explain what SOQL and SOSL are.


Answer: SOQL (Salesforce Object Query Language) is used for querying specific objects
in the Salesforce database. SOSL (Salesforce Object Search Language) is used for
searching text, email, and phone fields across multiple objects.

6. Describe a scenario where you used Visualforce.

Answer: I used Visualforce to create a custom user interface for a specific client need. It
involved customizing a page layout and integrating it with Apex controllers for specific
functionalities.

7. What are some of the limitations of Apex?

Answer: Apex has governor limits to ensure shared resources are used efficiently, like
limits on memory usage, number of records processed, and API callouts in a single
transaction.

8. Can you explain what a trigger is in Salesforce?

Answer: A trigger in Salesforce is a piece of Apex code that executes before or after data
manipulation operations like insert, update, or delete. It’s used to perform custom
actions automatically.

9. How do you ensure code quality in Salesforce?

Answer: Ensuring code quality involves writing clean, efficient Apex code, following best
practices, conducting peer reviews, and performing unit testing to cover various
scenarios.

10. What is a Sandbox, and how is it used?

Answer: A Sandbox in Salesforce is a copy of the production environment. It’s used for
development, testing, and training without affecting the live environment.

11. Explain what a workflow rule is.

Answer: A workflow rule automates certain processes based on specific criteria. For
example, it can automatically send an email alert, create tasks, or update fields when a
record meets certain conditions.

12. How do you handle debugging in Salesforce?

Answer: Debugging in Salesforce involves using the Developer Console and debug logs
to trace and resolve issues. System.debug statements in Apex help in tracking variable
values and process flows.

13. What are custom objects and fields in Salesforce?


Answer: Custom objects are tables in Salesforce that store specific business data.
Custom fields are added to these objects to store data unique to an organization’s
needs.

14. Describe a challenging project you worked on in Salesforce.

Answer: I worked on a project that involved integrating Salesforce with an external


inventory management system. It required API integration, custom Apex code, and
meticulous testing to ensure seamless data synchronization.

15. How do you stay updated with new Salesforce features?

Answer: I follow Salesforce blogs, attend webinars, and participate in community


events. Additionally, I regularly explore the Salesforce release notes.

16. What is batch Apex, and why is it used?

Answer: Batch Apex is used to process large numbers of records asynchronously. It’s
useful when operations can’t be processed in a single transaction due to governor
limits.

17. Can you explain the MVC architecture in Salesforce?

Answer: MVC in Salesforce stands for Model-View-Controller. It separates the


application’s data model (Model), UI (View), and business logic (Controller) to facilitate
easier management and scalability.

18. Describe how you have used Lightning Components.

Answer: I used Lightning Components to build reusable and dynamic user interfaces in
Salesforce. This involved creating both Aura and Web Components, depending on the
project requirement.

19. What strategies do you use for effective time management in project
delivery?

Answer: I prioritize tasks based on urgency and importance, break down large tasks into
manageable chunks, and use tools like calendars and to-do lists for better organization.

20. How do you approach learning new Salesforce features or products?

Answer: I approach it through hands-on experimentation in a Sandbox, online courses,


Salesforce Trailhead, and by joining Salesforce developer groups to learn from peers.

Interview Questions and Answers for a Mid-Level Salesforce Developer

1. How do you approach writing test classes in Salesforce?


Answer: I ensure test classes cover various scenarios and assert results to confirm
code functionality. I aim for high test coverage but prioritize meaningful tests over
simply meeting coverage percentages.

2. Can you explain the concept of Governor Limits and how you manage them?

Answer: Governor Limits are Salesforce’s way of ensuring resource allocation fairness. I
manage them by optimizing code, using bulkified operations, and efficient SOQL
queries.

3. Describe an instance where you optimized a Salesforce implementation.

Answer: I optimized a Salesforce implementation by refactoring legacy code, improving


SOQL query efficiency, and implementing batch processes to handle large data sets
more effectively.

4. How do you ensure data security in Salesforce applications?

Answer: Data security is ensured through proper profile and permission set
configurations, field-level security, and using sharing rules and roles to control record
access.

5. Explain the use of change sets in Salesforce.

Answer: Change sets are used for deploying components from one Salesforce org to
another. They are particularly useful for transferring customizations in a controlled and
traceable manner.

6. Discuss a complex Apex trigger you have written.

Answer: I wrote a complex trigger that handled multiple related objects, ensuring data
integrity across them. It involved careful bulkification and error handling to comply with
governor limits and robust functionality.

7. How have you used Visualforce in your projects?

Answer: I’ve used Visualforce for creating bespoke user interfaces, integrating with Apex
controllers for advanced functionalities, and ensuring they are responsive and efficient.

8. Describe your experience with Salesforce integrations.

Answer: I’ve integrated Salesforce with external systems using REST and SOAP APIs.
This involved understanding external systems, mapping data, and handling
authentication and error scenarios.

9. What are your strategies for managing large data volumes in Salesforce?

Answer: Managing large data volumes involves using proper indexing, archiving old
records, optimizing page layouts, and using efficient query filters.
10. How do you keep abreast of new Salesforce features and updates?

Answer: I regularly check Salesforce release notes, participate in developer forums, and
engage in continuous learning through Trailhead and other online resources.

11. Explain the use and benefits of Lightning Web Components.

Answer: Lightning Web Components (LWC) are a modern framework for building fast,
efficient, and reusable UI components. They leverage web standards and improve
performance and user experience.

12. Describe a situation where you had to troubleshoot a complex issue in


Salesforce.

Answer: I troubleshooted a complex issue involving asynchronous Apex and batch job
conflicts. It required in-depth analysis of the execution logs and understanding the
interdependencies within the system.

13. What is your approach to deploying Salesforce applications across different


environments?

Answer: I use a combination of change sets and version control systems like Git. I follow
best practices for deployment, including thorough testing in a staging environment
before production deployment.

14. How do you handle user adoption challenges in a new Salesforce


implementation?

Answer: I address user adoption by providing comprehensive training, creating user-


friendly documentation, and implementing feedback mechanisms to continuously
improve the system.

15. What experience do you have with Salesforce mobile app customization?

Answer: I have customized Salesforce mobile apps using the Salesforce Mobile SDK,
optimizing layouts for mobile and ensuring consistent user experience across devices.

16. How would you handle a request for a feature that’s not natively supported
by Salesforce?

Answer: I would first explore AppExchange for suitable add-ons. If unavailable, I’d
assess the feasibility of custom development using Apex or LWC, always considering
maintenance and scalability.

17. Can you discuss your experience with continuous integration/continuous


deployment in Salesforce?
Answer: I have experience setting up CI/CD pipelines using tools like Jenkins and
Salesforce DX, which streamline the development process and reduce errors in
deployments.

18. How do you approach documentation in your Salesforce projects?

Answer: Good documentation is crucial. I document both the technical aspects and
user guides, ensuring they are clear, concise, and updated regularly.

19. Describe your experience with Salesforce reporting and analytics.

Answer: I have created complex reports and dashboards, utilizing features like report
formulas, joined reports, and dynamic dashboards to provide actionable insights.

20. How do you balance customization with maintainability in Salesforce?

Answer: Balancing customization with maintainability involves adhering to Salesforce


best practices, avoiding over-customization, and ensuring any custom code is well-
documented and scalable.

Interview Questions and Answers for a Senior Salesforce Developer

1. How do you lead a Salesforce project from conception to deployment?

Answer: I initiate by gathering detailed requirements, planning the architecture, and


then guide the development and testing phases. Finally, I oversee the deployment,
ensuring a smooth transition and post-deployment support.

2. Explain how you manage complex integrations in Salesforce.

Answer: For complex integrations, I analyze the external systems, design robust
integration patterns using REST/SOAP APIs or middleware, and ensure data consistency
and error handling are meticulously addressed.

3. Describe your approach to optimizing Salesforce performance in large-scale


implementations.

Answer: In large-scale implementations, I focus on efficient data modeling, optimize


Apex and SOQL for performance, and leverage Salesforce features like batch processes
and queueable Apex to manage load.

4. How do you ensure high-quality code in your Salesforce team?

Answer: I enforce coding standards, conduct regular code reviews, and advocate for
comprehensive unit testing. Additionally, I encourage knowledge sharing sessions to
maintain high code quality across the team.

5. Discuss a challenging Salesforce migration project you managed.


Answer: I managed a migration project where we shifted a complex Salesforce instance
to Lightning. This involved re-engineering several components, extensive testing, and
training users on the new interface.

6. How do you mentor junior developers in Salesforce?

Answer: I mentor juniors by providing clear guidance on best practices, encouraging


them to solve problems independently, and offering constructive feedback. I also
recommend resources like Trailhead for self-paced learning.

7. Describe how you handle conflicting requirements from different


stakeholders in a Salesforce project.

Answer: I address conflicting requirements by facilitating discussions between


stakeholders to understand their needs and priorities, and then propose solutions that
align with the project’s overall goals.

8. What’s your strategy for keeping up with the frequent updates and changes
in the Salesforce ecosystem?

Answer: My strategy involves regularly reviewing Salesforce release notes, participating


in developer forums and webinars, and dedicating time for hands-on experimentation
with new features.

9. How do you assess and mitigate risks in Salesforce development projects?

Answer: I assess risks by analyzing project requirements and potential challenges.


Mitigation involves strategic planning, contingency measures, and ensuring robust
testing is in place.

10. Explain how you manage user adoption for new Salesforce features or
systems.

Answer: I manage user adoption by conducting training sessions, creating user-friendly


documentation, and implementing a feedback mechanism to address concerns and
improve the system continuously.

11. Describe your experience with advanced Apex programming.

Answer: My experience with advanced Apex includes developing complex triggers,


batch Apex, and asynchronous Apex for handling bulk data operations and complex
business logic.

12. How do you approach designing a scalable and maintainable Salesforce


architecture?
Answer: Designing scalable architecture involves careful planning of data structures,
anticipating future growth, and adhering to Salesforce best practices to ensure easy
maintenance and upgrades.

13. Discuss how you have used Einstein Analytics in your projects.

Answer: In my projects, I have utilized Einstein Analytics for advanced data analysis,
creating predictive models, and delivering customized dashboards to provide deeper
insights into business performance.

14. What is your approach to troubleshooting and resolving critical issues in


Salesforce?

Answer: My approach involves thorough analysis of the issue, replicating the problem in
a test environment, implementing a fix, and conducting rigorous testing before
deploying the solution to production.

15. Explain your experience in automating business processes in Salesforce.

Answer: I have automated business processes using Workflow Rules, Process Builder,
and Flow, optimizing operations, reducing manual work, and enhancing overall
efficiency.

16. How do you balance the use of declarative vs. programmatic capabilities in
Salesforce?

Answer: I balance these by using declarative tools for simpler requirements and reserve
programmatic solutions for complex scenarios, ensuring the system remains flexible
and maintainable.

17. Describe a time you had to make a critical decision in a Salesforce project.

Answer: I made a critical decision in a project where we had to choose between custom
development and an off-the-shelf AppExchange product. It involved analyzing cost,
scalability, and long-term maintenance.

18. How do you approach data migration and cleansing in Salesforce?

Answer: Data migration and cleansing involve planning the data mapping, using tools
like Data Loader for migration, and implementing scripts or tools for cleansing and
deduplication.

19. Discuss your experience with Salesforce mobile application development.

Answer: I have developed Salesforce mobile applications using Salesforce Mobile SDK,
focusing on user experience, performance, and offline capabilities.

20. How do you ensure ongoing success and evolution of a Salesforce


implementation post-deployment?
Answer: Post-deployment, I ensure success by monitoring system performance,
gathering user feedback, and regularly updating the system with enhancements and
new Salesforce features.

Scenario-Based Interview Questions and Answers for a Salesforce Developer

1. Scenario: A Salesforce implementation is running into frequent governor


limit issues. How would you address this?

Answer: I would perform a thorough analysis to identify the specific limits being hit,
optimize the code by reducing SOQL queries, using bulkified patterns, and
implementing more efficient data handling practices.

2. Scenario: You’re tasked with integrating Salesforce with an external ERP


system. Describe your approach.

Answer: My approach involves understanding the ERP system’s capabilities, defining


the data flow and synchronization frequency, and using appropriate integration
methods like REST API or middleware solutions for a seamless integration.

3. Scenario: The sales team needs a custom Salesforce mobile app. How do
you proceed?

Answer: I’d start by gathering detailed requirements from the sales team, then design a
user-friendly interface focusing on their key needs, and use Salesforce Mobile SDK to
develop and deploy the app.

4. Scenario: Users report that a specific Salesforce process is too slow. What
steps do you take?

Answer: I’d first replicate the issue in a test environment, analyze the process for
inefficiencies, possibly optimize workflow rules or process builder flows, and ensure
that any Apex code is bulkified and efficient.

5. Scenario: You need to migrate a large amount of data into Salesforce. How
do you ensure data integrity?

Answer: I would use a reliable ETL tool, thoroughly map data fields, perform data
cleansing before migration, and conduct extensive testing post-migration to ensure data
integrity.

6. Scenario: A project requires significant customization in Salesforce. How do


you balance custom vs. out-of-the-box features?
Answer: I balance this by evaluating the long-term impact of customizations, preferring
out-of-the-box features when feasible, and ensuring custom development is
maintainable and scalable.

7. Scenario: You’re leading a team transitioning from Salesforce Classic to


Lightning. What’s your strategy?

Answer: My strategy involves training the team on Lightning, conducting an audit of our
existing setup, prioritizing components for migration, and implementing changes in
phases to ensure a smooth transition.

8. Scenario: A client wants real-time analytics from Salesforce data. How do


you fulfill this requirement?

Answer: I would leverage Einstein Analytics or a similar BI tool to create dynamic


dashboards and reports, ensuring they provide real-time insights based on the client’s
specific data points.

9. Scenario: Your organization wants to implement a new Salesforce module.


Describe your approach to training users.

Answer: I’d develop a comprehensive training plan including hands-on sessions,


custom documentation, and support channels. I’d also provide continuous learning
opportunities post-implementation.

10. Scenario: You discover a security flaw in your Salesforce setup. What
actions do you take?

Answer: Immediately, I’d assess the scope of the flaw, implement a fix or workaround,
and conduct a security audit to prevent similar issues. I’d also review and update
security best practices with the team.

11. Scenario: A business process requires automation in Salesforce. How do


you decide between Flow, Process Builder, and Apex?

Answer: I choose based on the complexity and needs of the process – Flow for complex
logic, Process Builder for straightforward automation, and Apex for scenarios needing
advanced coding.

12. Scenario: You’re asked to improve the Salesforce UX for a better customer
experience. What’s your plan?

Answer: My plan involves analyzing user feedback, simplifying navigation, customizing


page layouts for efficiency, and using Lightning components to enhance the overall user
experience.

13. Scenario: The marketing team needs a complex campaign management


solution in Salesforce. How do you tackle this?
Answer: I would analyze their requirements, leverage Salesforce’s campaign
management features, and potentially integrate with a marketing automation tool for
enhanced capabilities.

14. Scenario: You need to ensure high data quality in Salesforce. What steps do
you take?

Answer: I’d implement validation rules, duplicate rules, and regular data audits.
Additionally, I’d train users on data entry best practices and use automation to assist in
maintaining data quality.

15. Scenario: There’s a need to scale up Salesforce for growing business


demands. How do you ensure scalability?

Answer: To ensure scalability, I focus on efficient data modeling, leverage Salesforce’s


scalable features like custom metadata types, and continuously monitor and optimize
system performance.

16. Scenario: A critical update is required in the Salesforce system during peak
business hours. How do you handle it?

Answer: I’d plan the update meticulously to minimize disruption, communicate clearly
with stakeholders about the timing, and ensure a rollback plan is in place in case of
unforeseen issues.

17. Scenario: You are asked to reduce the Salesforce licensing costs for your
company. What approach do you take?

Answer: I’d conduct a thorough audit of current license usage, identify underutilized
licenses or features, and strategize on optimizing license allocation without impacting
business operations.

18. Scenario: You’re tasked with enhancing the Salesforce mobile experience
for remote sales teams. What are your key focus areas?

Answer: My focus areas would be on optimizing the mobile UI for ease of use, ensuring
offline capabilities, and integrating essential features that cater to the unique needs of
remote sales teams.

19. Scenario: The organization requires a custom report generation tool within
Salesforce. What’s your strategy?

Answer: I’d evaluate the specific reporting needs, develop custom reports or
dashboards using SOQL and Apex if needed, and ensure they are user-friendly and
provide actionable insights.

20. Scenario: There’s a requirement to integrate social media data into


Salesforce. How do you achieve this?
Answer: I would use Salesforce’s Social Studio or a third-party integration tool to
connect social media channels, ensuring seamless data flow and alignment with the
organization’s social media strategy.

Technical/Coding Interview Questions and Answers for Salesforce Developers

1. What is a SOQL query and how does it differ from SQL?

Answer: SOQL, Salesforce Object Query Language, is specifically designed for


Salesforce data. Unlike SQL, it cannot be used to perform operations like INSERT or
DELETE, and focuses on querying the data within Salesforce’s framework.

2. Explain the concept of Governor Limits in Salesforce.

Answer: Governor Limits are Salesforce’s way of enforcing limits on the usage of
resources like memory, SOQL queries, DML statements, etc., to ensure that no single
process or code monopolizes shared resources.

3. How do you perform upsert operations in Apex?

Answer: In Apex, upsert operations are performed using the upsert statement. It creates
new records and updates existing ones based on the specified key field.

4. Describe the use of triggers in Salesforce.

Answer: Triggers in Salesforce are used to perform custom actions before or after
changes to Salesforce records, such as updates, inserts, or deletions. They’re written in
Apex and can be used to automate complex business logic.

5. What is a custom controller in Salesforce?

Answer: A custom controller is an Apex class that implements all the logic for a page
without leveraging the standard controller provided by Salesforce, giving developers
complete control over the behavior of a Visualforce page.

6. Explain the role of test classes in Salesforce.

Answer: Test classes in Salesforce are used to ensure that Apex classes and triggers
work as expected. They are necessary for deploying code to production and are crucial
for maintaining code quality and integrity.

7. How do you handle exceptions in Apex?

Answer: Exceptions in Apex are handled using try, catch, and finally blocks. You can
write code to gracefully handle exceptions and ensure that the user gets meaningful
error messages.

8. What are batch Apex classes and where are they used?
Answer: Batch Apex classes are used for processing large data sets that exceed normal
processing limits. They allow you to define a job that can be divided into manageable
chunks, processed separately, and executed in a serial manner.

9. Describe a scenario where you would use a Visualforce page.

Answer: Visualforce pages are used when a custom user interface is needed that can’t
be achieved with Salesforce’s standard UI. For example, creating a complex form that
includes custom logic or styling.

10. Explain the use of the @future annotation in Apex.

Answer: The @future annotation in Apex is used for executing methods asynchronously.
It’s useful for running processes in a separate thread, especially when you are dealing
with callouts to external services.

11. How do you secure Apex code against SOQL injection?

Answer: To protect against SOQL injection, it’s important to avoid dynamic SOQL
queries when possible. If dynamic queries are necessary, use binding variables instead
of string concatenation to create the query.

12. What are the different types of collections in Apex?

Answer: In Apex, there are three types of collections: Lists (ordered, indexable
collections), Sets (unordered collections of unique elements), and Maps (collections of
key-value pairs).

13. How do you implement error handling in batch Apex?

Answer: Error handling in batch Apex can be implemented using try-catch blocks within
the execute method, and by overriding the finish method to handle post-processing and
notification of the batch job status.

14. What is the purpose of the Schema Builder in Salesforce?

Answer: Schema Builder provides a dynamic environment to add new objects, fields,
and relationships to your schema. It is a powerful tool for designing and modifying your
data model visually.

15. Describe the process of creating a custom web service in Salesforce.

Answer: Custom web services in Salesforce are created using Apex. You define a global
class with the webservice keyword, write methods to expose as web service operations,
and then deploy the service for external access.

16. How can you call an external REST service from Apex?
Answer: To call an external REST service from Apex, you use the HttpRequest and
HttpResponse classes. You set up the request URL, headers, method (GET, POST, etc.),
and then send the request using the Http class.

17. What is the purpose of the sharing keyword in Apex?

Answer: The with sharing keyword is used in Apex classes to enforce the sharing rules
that apply to the current user. This ensures that users can only access records that
they’re permitted to access based on the organization’s sharing policies.

18. Explain how you can debug Apex code.

Answer: Apex code can be debugged using the Developer Console or debugging tools
available in the Salesforce IDE. Debug logs can be generated to track the execution of
code, monitor variables, and observe system processes.

19. What is a wrapper class in Apex?

Answer: A wrapper class in Apex is a custom class defined by the developer that wraps
around standard or custom objects. It’s often used to combine data from different
objects or add additional attributes for use in Visualforce pages.

20. How do you ensure that an Apex class is deployable to production?

Answer: To ensure an Apex class is deployable to production, it must have at least 75%
code coverage from unit tests, and all those tests must pass without errors.
Additionally, the code should adhere to Salesforce best practices for maintainability
and efficiency.

1.1 Overall Best Practices in Salesforce Development (Declarative and Coding)

• Declarative Development Best Practices:

o Use Standard Objects and Fields: Whenever possible, leverage out-of-


the-box Salesforce objects and fields to avoid reinventing the wheel.

o Use Process Builder and Flow: For automating business logic, use
Process Builder or Flow rather than triggers, as they provide declarative
solutions and are easier to maintain.

o Keep It Simple: Avoid creating overly complex flows or process builders.


Complex automations can lead to performance issues and harder
debugging.
o Use Validation Rules and Formula Fields: These can ensure data
integrity and simplify business logic without code.

• Apex Code Best Practices:

o Bulkify Your Code: Always ensure that your Apex code is bulkified. Avoid
SOQL queries or DML operations inside loops.

o Governor Limits: Be aware of Salesforce governor limits. Write efficient


code to stay within limits, such as using LIMIT clauses and using batch
processing when necessary.

o Test Coverage: Ensure that all Apex code is unit tested with at least 75%
code coverage. Tests should be robust and cover different edge cases.

o Keep SOQL Queries Outside Loops: Always avoid querying data inside a
loop to prevent hitting governor limits.

o Use Custom Settings and Custom Metadata Types: Instead of


hardcoding values, use Custom Settings and Custom Metadata Types to
store configuration data.

o Document and Comment Code: Properly document your code so others


can easily understand and maintain it.

1.2 Explain Objects and Relationships in Salesforce

• Objects in Salesforce are database tables that store data. There are two types:

o Standard Objects: Predefined objects provided by Salesforce, such as


Account, Contact, Opportunity, etc.

o Custom Objects: User-defined objects to store information unique to


your business.

• Relationships define how objects are related to each other. Salesforce supports
different relationship types:

o Lookup Relationship: A one-to-one relationship where one object


references another. The referenced record can exist independently.

o Master-Detail Relationship: A one-to-many relationship where the detail


(child) record cannot exist without the master (parent) record. The child
record inherits permissions from the parent.

o Many-to-Many Relationship: Implemented using a junction object that


links two objects.
1.3 Difference Between Lookup and Master-Detail Relationship

• Lookup Relationship:

o One object "looks up" to another but the related record can exist
independently.

o Deletion of the parent record doesn’t delete the child record.

o The child record can exist without the parent record.

• Master-Detail Relationship:

o The detail record is tightly dependent on the master record. The child
(detail) record cannot exist without the master.

o If the master record is deleted, all related child records are also deleted
(cascade delete).

o The child record inherits ownership and security settings from the master.

1.4 Why Do You Need a Junction Object?

A junction object is used to model a many-to-many relationship between two objects.


In Salesforce, many-to-many relationships cannot be directly represented using
standard relationships. Instead, a junction object is created to link two objects through
two Master-Detail relationships.

Example: An opportunity can be linked to multiple contacts, and each contact can be
linked to multiple opportunities. To represent this relationship, you would create a
junction object like "Opportunity Contact Role" that links opportunities and contacts.

1.5 Explain Roles, Profiles, and Permission Sets

• Roles: Define the hierarchy of users in the organization. A user's role determines
their visibility to data based on the role hierarchy. Higher roles can see records
owned by lower roles.

• Profiles: Define what a user can do in Salesforce, such as permissions on


objects, fields, and page layouts. Every user must have one profile.

• Permission Sets: Allow you to extend additional permissions to users without


changing their profile. Permission sets are used to grant specific access rights to
users based on business needs.
1.6 Talk About Salesforce Governor Limits

Salesforce enforces governor limits to ensure efficient use of resources and maintain
the performance of its multi-tenant architecture. Some important governor limits
include:

• SOQL Queries: 100 queries per transaction.

• DML Statements: 150 DML operations per transaction.

• Apex CPU Time: Maximum execution time for Apex code (10,000 ms per
transaction).

• Heap Size: Maximum memory allowed for Apex variables (6 MB for synchronous
operations, 12 MB for asynchronous operations).

• Concurrent Requests: Limitation on the number of concurrent requests.

It’s important to write optimized and bulkified code to avoid hitting these limits.

1.7 What's the Most and the Least Restricted Salesforce Security Models?

• Most Restricted:

o Sharing Rules: The Private sharing model is the most restrictive. Each
record is only visible to the record owner and users above them in the role
hierarchy.

• Least Restricted:

o Public Read/Write: The Public sharing model allows all users to see and
modify all records. This is the least restrictive model.

1.8 How Many Junction Objects Can You Have on One Object?

There’s no hard limit on the number of junction objects you can create for a single
object, but you are limited by the maximum number of relationships a single object can
have. Salesforce allows up to 40 total relationships per object, including lookup and
master-detail relationships.

For many-to-many relationships, this means you can create multiple junction objects,
but the total number of relationships per object (including these junctions) cannot
exceed the limit of 40.
1.9 How Would You Code Error Tracking in Your Application, So That Your End Users
Can Access This Information?

To track and present errors effectively to users:

1. Create a Custom Error Object: You can create a custom object called
Error_Log__c to store error details, such as error type, message, user, timestamp,
and affected records.

2. Log Errors in Apex: In your Apex code, use try-catch blocks to capture
exceptions and then create new records in the Error_Log__c object with the
relevant error details.

apex

CopyEdit

try {

// your logic here

} catch (Exception e) {

Error_Log__c errorLog = new Error_Log__c(

Error_Message__c = e.getMessage(),

Stack_Trace__c = e.getStackTraceString(),

User__c = UserInfo.getUserId(),

Record_Id__c = yourRecordId

);

insert errorLog;

3. Notify Users (Optional): You can send an email notification to admins or


relevant users if an error occurs.

4. Provide a User-Friendly UI: On the front end (e.g., a Visualforce page or


Lightning Component), you can create a custom error display that pulls from the
Error_Log__c object, allowing end users to view details of the error, or request
assistance.

5. Use Debug Logs: For internal troubleshooting, Salesforce Debug Logs can be
used to capture detailed logs for developers when tracking complex issues in
production.
By combining the above strategies, you can create an effective error tracking system
that is both developer-friendly and user-accessible.

2.1 What is Org-Wide Default (OWD)?

Org-Wide Default (OWD) defines the baseline level of access to records for all users in
an organization. It determines how records are shared by default across the entire
Salesforce org. OWD settings are the foundation for setting up sharing rules and
permissions.

The available OWD settings are:

• Private: Only the record owner and users above them in the role hierarchy can
view and edit the record.

• Public Read Only: All users can view the record, but only the owner and users
above them in the role hierarchy can edit it.

• Public Read/Write: All users can view and edit the record.

By setting OWD, you can control who has access to the records and build further
sharing strategies on top of this baseline.

2.2 Sharing Rules vs. Manual Sharing Rules: When and Why Would You Use Them?

• Sharing Rules:

o Purpose: Sharing rules are used to extend record access to groups of


users, beyond the OWD settings.

o Types: You can create sharing rules based on role hierarchy, public
groups, or territory.

o When to Use: Use sharing rules when you need to grant broader access
to specific records based on criteria such as record owner or other field
values.

o Example: Share all opportunities where the amount is greater than


$1,000 with a specific public group.

• Manual Sharing Rules:

o Purpose: Manual sharing allows individual users to share specific records


with other users, groups, or roles.
o When to Use: Manual sharing is used when a user needs to explicitly
share access to a specific record with someone, outside the normal
sharing model.

o Example: A user manually shares a record with a colleague because that


colleague needs to work on it.

Key Difference: Sharing rules are automatic and apply to groups of records, while
manual sharing is more granular and applies to individual records.

2.3 What is Salesforce Shield?

Salesforce Shield is a suite of advanced security tools designed to help you secure
your Salesforce data and ensure compliance with regulatory standards. It includes the
following features:

• Field Audit Trail: Allows you to track the history of changes to fields for up to 10
years.

• Platform Encryption: Provides encryption at rest for sensitive data stored in


Salesforce, ensuring that data is protected both at rest and in transit.

• Event Monitoring: Tracks and logs user activities across the Salesforce platform,
allowing admins to monitor how users interact with data and applications.

• Enhanced Encryption: Provides encryption capabilities for custom fields, files,


and attachments.

Salesforce Shield is useful for industries and organizations that need enhanced data
security and compliance capabilities, such as in healthcare, financial services, or
government.

2.4 What is Custom Settings? Show How to Create One.

Custom Settings are a type of custom object that provide a way to store application
configuration data that can be accessed in Apex code or formulas. There are two types
of custom settings:

• List Custom Settings: Store data that is accessible by all users in the org.

• Hierarchy Custom Settings: Store data specific to individual users or profiles


and allow for inheritance.

To create a Custom Setting:

1. Go to Setup > Custom Settings.


2. Click New.

3. Provide a Name and Object Name for the custom setting (e.g., API_Config__c).

4. Select List or Hierarchy based on your needs.

5. Save your settings.

Example: If you want to store API configuration values, you would create a custom
setting to store keys, endpoint URLs, etc., and reference those values in Apex code.

To access custom setting data in Apex:

apex

CopyEdit

API_Config__c config = API_Config__c.getValues('Default_Config');

String endpoint = config.Endpoint_URL__c;

2.5 What’s the Difference Between Scheduled Jobs and Apex Jobs?

• Scheduled Jobs:

o Purpose: Scheduled jobs are used to run Apex code at specified times or
intervals (e.g., daily, weekly).

o Use Case: Ideal for automation that needs to run on a regular schedule
without user intervention, such as batch data processing or sending
regular reports.

o How to Schedule: Use the System.schedule method in Apex to schedule


a class to run at a specific time.

Example:

apex

CopyEdit

String cronExp = '0 0 12 * * ?'; // Run daily at noon

MyScheduledClass sch = new MyScheduledClass();

System.schedule('Daily Job', cronExp, sch);

• Apex Jobs (Asynchronous Jobs):


o Purpose: Apex jobs include Queueable, Batch, and Future methods that
allow you to run long-running or resource-intensive operations
asynchronously, outside the main thread of execution.

o Use Case: Useful for operations that can be executed in the background
without blocking user interaction, such as sending bulk emails or
performing calculations on large datasets.

2.6 How Can You Whitelist a Website?

To whitelist a website in Salesforce, you typically use Remote Site Settings. These
settings define which external URLs are allowed to be accessed from Salesforce.

To whitelist a website:

1. Go to Setup.

2. In the Quick Find box, type Remote Site Settings.

3. Click New Remote Site.

4. Provide a Name and the URL of the site you want to whitelist.

5. Optionally, check the Active box to enable the site.

6. Save the settings.

This allows Salesforce to make outbound requests to the specified URL.

2.7 What is a Platform Event and How Would You Create One?

A Platform Event is a custom event in Salesforce that enables asynchronous


communication between different parts of a system. It allows for real-time event-based
integration and can be used to trigger workflows, processes, or even external systems.

To create a Platform Event:

1. Go to Setup.

2. In the Quick Find box, type Platform Events.

3. Click New Platform Event.

4. Enter a Name (e.g., Order_Received__e).

5. Define the event fields that will be part of the event.

6. Save the event.


Once created, you can publish events through Apex or integrate with external systems
that can publish events to Salesforce. For example, to publish an event using Apex:

apex

CopyEdit

Order_Received__e event = new Order_Received__e(OrderId__c='12345');

Database.saveResult result = EventBus.publish(event);

2.8 Explain Enabling Debug Logs

Debug Logs help developers trace issues by providing detailed logs about what
happens when a process runs in Salesforce, including user interactions, data changes,
and system operations.

To enable debug logs:

1. Go to Setup.

2. In the Quick Find box, type Debug Logs.

3. Click New or select an existing log to modify.

4. Choose the user whose actions you want to log (usually yourself or a user
experiencing an issue).

5. Set the log level (e.g., DEBUG, ERROR).

6. Save the settings.

You can view the logs by navigating to the Debug Logs page and clicking on the log
entries.

2.9 What is a Connected App?

A Connected App in Salesforce is an application that integrates with Salesforce using


APIs. It allows third-party applications to authenticate and interact with Salesforce data
and services.

To create a Connected App:

1. Go to Setup.

2. In the Quick Find box, type App Manager.

3. Click New Connected App.


4. Enter details such as the App Name, API Name, and Contact Email.

5. Enable OAuth settings and define the OAuth scopes (permissions) for the app.

6. Save the app.

The connected app generates credentials (Client ID and Client Secret) that are used to
authenticate external applications via OAuth 2.0.

2.10 How Do You Make an Apex Class Available to a Certain Profile?

To make an Apex class available to a specific profile, you need to modify the Profile
Settings:

1. Go to Setup.

2. In the Quick Find box, type Profiles and select the profile you want to modify.

3. Scroll to the Apex Class Access section.

4. Click Edit.

5. Select the Apex class you want to make available from the list of available
classes.

6. Save the changes.

This allows only users with the specified profile to access and execute the Apex class.

3.1 What Declarative Tool Can You Use to Send Emails?

In Salesforce, you can use several declarative tools to send emails, but the most
common ones are:

• Process Builder: You can use Process Builder to send emails as part of an
automated workflow when certain criteria are met.

o Steps:

1. Create a new Process in Process Builder.

2. Define the criteria for the process (e.g., when a record is created or
updated).

3. Add an action and select Email Alerts.

4. Choose an existing Email Template or create a new one.

5. Define the recipients (e.g., record owner, related user, etc.).


• Flow: You can send emails via Flows as well by using the Send Email action in
Flow.

o Steps:

1. Create or open an existing Flow.

2. Add the Send Email action.

3. Define the email template, recipient, subject, and body.

4. Activate the flow.

• Email Alerts: Email Alerts can be set up within Workflow Rules or Process
Builder to trigger emails when certain conditions are met.

3.2 Name Different Types of Flows

Salesforce offers several types of Flows for different purposes:

1. Screen Flow:

o Used to guide users through a series of screens to collect or display


information. Typically used in a user interface (e.g., for users to enter
data).

o Example: Collecting feedback from users, guiding through a process, etc.

2. Autolaunched Flow (No Trigger):

o Runs in the background without requiring user interaction. These flows


are typically triggered by other processes, such as Process Builder, or
manually by a user/admin.

o Example: Updating records automatically based on certain conditions.

3. Autolaunched Flow (With Trigger):

o This type of flow is triggered automatically when a record is created,


updated, or deleted. It doesn’t require user interaction.

o Example: Automatically updating related records when an opportunity


stage changes.

4. Scheduled Flow:

o Used for flows that need to run at scheduled times. Ideal for batch
operations or periodic tasks like sending out reports or updating records
daily.

o Example: Sending out weekly emails or updating data in bulk.


3.3 Talk About Similarities Between Validation Rules and Flows

Both Validation Rules and Flows can be used to ensure data consistency and enforce
business rules in Salesforce. Here are their similarities:

• Data Integrity: Both can enforce business logic to ensure that only valid data is
entered into Salesforce.

• Error Messages: Both can display error messages when the validation or logic
fails.

o Validation Rule: Displays a custom error message when conditions are


not met.

o Flow: Can show a screen or use a Fault path to display an error message
or handle the issue.

• User Interaction: Validation Rules are typically triggered when saving a record,
while Flows can be used to guide users through a process and prompt for
corrections or inputs.

Key Differences:

• Validation Rules are simpler and focus on data validation. Flows are more
complex and provide greater flexibility for automation, data manipulation, and
user interaction.

3.4 Where Would You Use Custom Metadata Types, Custom Settings, and Labels?

• Custom Metadata Types:

o Used to store application configuration data that can be packaged and


deployed across different orgs. It is ideal for managing settings that
should not change frequently, like API keys or integration settings.

o Example Use: You might store integration configurations (e.g., endpoint


URLs, authentication tokens) that you want to easily deploy across orgs.

Code Snippet:

apex

CopyEdit

MyMetadataType__mdt config = [SELECT MasterLabel, My_Field__c FROM


MyMetadataType__mdt WHERE MasterLabel = 'ConfigName' LIMIT 1];

System.debug(config.My_Field__c);

• Custom Settings:
o Used for storing application-specific data, similar to Custom Metadata,
but they can be used to store user or profile-specific data as well.

o Example Use: Storing default values or thresholds that can be accessed


globally by the app or organization.

• Custom Labels:

o Used to store text that can be referenced in code, such as error


messages, user-facing text, or display names, which can be translated in
different languages.

o Example Use: Defining error messages that will be shown to users based
on different contexts.

Example Use:

apex

CopyEdit

String errorMessage = Label.Invalid_Email_Error; // Reference to Custom Label

3.5 How Do You Handle Errors in Salesforce Flows?

In Salesforce Flows, errors can be handled using Fault Paths and Decision Elements:

1. Fault Path:

o Every Flow element can have a Fault path, which is triggered if an error
occurs while executing that element.

o Example: In a record update or creation action, if an error occurs (e.g.,


due to validation rule failure), the Flow can direct the user to a screen with
an error message.

2. Decision Elements:

o You can use Decision elements to check for specific conditions and
handle errors by providing alternative paths (e.g., showing an error
message if a required field is not filled).

Example:

• Add a Fault Path to a record update element. If an error occurs, navigate the
user to a screen that explains the problem.

3.6 What's the Difference Between Scheduled Flow and Scheduled Apex?
• Scheduled Flow:

o A Scheduled Flow runs at a specified time, like once a day, and it is ideal
for tasks such as batch processing, record updates, and email reminders.
It’s easier to set up and doesn’t require Apex code.

o Example: Scheduling a flow to update records once a day.

• Scheduled Apex:

o Scheduled Apex involves writing an Apex class that runs on a schedule.


You can create a class that implements Schedulable and use
System.schedule to define the schedule. This is typically used for more
complex logic or operations that cannot be accomplished declaratively
with Flows.

Code Example for Scheduled Apex:

apex

CopyEdit

public class MyScheduledClass implements Schedulable {

public void execute(SchedulableContext context) {

// Your scheduled logic goes here

List<Account> accountsToUpdate = [SELECT Id FROM Account WHERE


LastModifiedDate < LAST_N_DAYS:30];

for(Account acc : accountsToUpdate) {

acc.Status__c = 'Inactive';

update accountsToUpdate;

// To schedule it

String cronExp = '0 0 0 1 1 ?'; // Run yearly on January 1st

MyScheduledClass mySched = new MyScheduledClass();

System.schedule('Yearly Job', cronExp, mySched);


Key Difference: Scheduled Flows are declarative and easier to set up but limited to
Flow capabilities, while Scheduled Apex allows for more complex logic and greater
flexibility but requires coding.

3.7 What Is There You CAN and CAN'T Do in Declarative Development and Apex?

Declarative Development (What You Can Do):

• Automation: Automate business processes using tools like Process Builder,


Flow, Workflow Rules, and Approval Processes.

• User Interface: Customize page layouts, create record types, add validation
rules, and create dynamic actions.

• Reports and Dashboards: Create custom reports, charts, and dashboards


without writing code.

• Data Management: Create and manage objects, fields, relationships, and


workflows declaratively.

Declarative Development (What You Can't Do):

• Complex Logic: Handling very complex or custom business logic, such as


intricate calculations or advanced integrations, may not be possible with
declarative tools.

• Bulk Data Processing: When dealing with large amounts of data or complex
data manipulations, declarative tools may run into governor limits.

• Custom UI Components: While Visualforce and Lightning Components offer


customization, declarative tools like page layouts or Flow don’t provide the level
of control that custom Apex or Lightning Web Components offer.

Apex Development (What You Can Do):

• Complex Logic: Apex allows for complex business logic, handling advanced
calculations and processes that can't be achieved through declarative tools.

• Bulk Data Processing: Apex can handle large data volumes and batch
processing (via Batch Apex or Queueable Apex).

• Custom Integrations: Apex can be used to integrate Salesforce with external


systems through APIs.

• Custom UI Components: You can build custom Visualforce pages and Lightning
Web Components (LWC) for advanced UI needs.

Apex Development (What You Can't Do):


• Simple Automations: Simple workflows or actions like sending an email when a
record is created can be done declaratively without needing Apex.

• No Direct UI Modifications: Apex can’t directly modify page layouts, views, or


simple UI elements. You’d need Visualforce or Lightning Components for
advanced UI changes.

In summary:

• Declarative tools are great for simple to moderately complex tasks, quick
implementations, and non-technical users.

• Apex is better suited for handling complex logic, large data volumes, and
advanced integrations but requires coding and deeper technical knowledge.

4.1 What is Trigger-Based Framework? What are Before and After Triggers?

A Trigger-Based Framework in Salesforce is a design pattern for organizing and


structuring Apex triggers to ensure they are scalable, maintainable, and adhere to best
practices. It focuses on separating business logic from trigger logic, ensuring that
triggers are not doing too much work, and maintaining the flexibility to manage various
trigger scenarios (like insert, update, delete).

• Before Triggers: These are executed before a record is saved to the database.

o Use Case: Before triggers are typically used for validation, setting default
field values, or preventing updates.

o Example: Validating if a field value is within an acceptable range before


saving.

• After Triggers: These are executed after a record is saved to the database. You
can’t modify the record’s fields in after triggers (since the record is already
committed to the database).

o Use Case: After triggers are useful for performing actions like sending
emails, creating related records, or updating external systems.

o Example: After creating a Contact, you can create a related Task.

Code Example:

apex

CopyEdit

trigger AccountTrigger on Account (before insert, after insert) {


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

// Before insert logic

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

// After insert logic

4.2 How Many Triggers Would You Create on One Object?

Salesforce allows only one trigger per object. However, you can have multiple trigger
events (e.g., before insert, after update, etc.) within a single trigger. It's best practice to
handle all events (insert, update, delete, undelete) in one trigger rather than creating
separate triggers.

Best Practice:

• Use a handler class to manage complex logic.

• Ensure the trigger follows the "one trigger per object" rule and calls a handler
class to keep it clean.

Example:

apex

CopyEdit

trigger AccountTrigger on Account (before insert, after insert, before update, after
update) {

if(Trigger.isBefore) {

// Call handler for before events

} else if(Trigger.isAfter) {

// Call handler for after events

}
4.3 How Do You Restrict Field Access in Apex?

You can restrict field-level access in Apex using the SObjectField class to check if the
current user has access to a specific field. This helps ensure that users do not interact
with fields they don’t have access to, based on their profile or permissions.

Example:

apex

CopyEdit

if(Schema.sObjectType.Account.fields.Name.isAccessible()) {

// The current user has access to the Name field on Account

String accountName = account.Name;

You can also use isUpdateable() or isCreateable() for other field-level access checks.

4.4 Talk About Async Apex

Asynchronous Apex is used when you need to run a long-running operation that
doesn’t need to complete immediately. It allows Salesforce to process data in the
background without blocking the user experience.

• Types of Asynchronous Apex:

1. Future Methods: Used for operations that should run in the background,
like making callouts or processing data.

2. Batch Apex: Used for processing large volumes of records in smaller


chunks.

3. Queueable Apex: Offers more flexibility than future methods, with


support for chaining jobs.

4. Scheduled Apex: Allows you to schedule an Apex job to run at specific


times.

4.5 What’s the Difference Between Future and Queueable Methods?

• Future Methods:

o Use Case: Best for simple asynchronous operations that don’t require
complex logic.
o Limitations: Cannot be chained, can only return void, and have fewer
limitations on data types.

o Example: Making an API callout asynchronously.

apex

CopyEdit

@future

public static void updateAccountName(String accountId) {

Account acc = [SELECT Id, Name FROM Account WHERE Id = :accountId];

acc.Name = 'New Name';

update acc;

• Queueable Apex:

o Use Case: More powerful than future methods, allowing for complex
logic, better error handling, and the ability to chain jobs.

o Example: A queueable job that processes a list of records.

apex

CopyEdit

public class MyQueueableClass implements Queueable {

public void execute(QueueableContext context) {

List<Account> accounts = [SELECT Id, Name FROM Account];

for(Account acc : accounts) {

acc.Name = 'Updated Name';

update accounts;

// To enqueue the job:

ID jobID = System.enqueueJob(new MyQueueableClass());


4.6 What is Invokable Apex?

Invokable Apex refers to Apex methods that are exposed to be called by Flows,
Process Builder, and other declarative tools. These methods are annotated with
@InvocableMethod to make them callable by these tools.

Use Case: You can create reusable logic that is called from a Flow without needing to
write Flow-specific logic.

Example:

apex

CopyEdit

public class MyInvocableClass {

@InvocableMethod(label='Update Account Name' description='Updates Account


Name')

public static void updateAccountName(List<Account> accounts) {

for(Account acc : accounts) {

acc.Name = 'Updated by Flow';

update accounts;

4.7 What’s the Difference Between SOQL and SOSL in Salesforce?

• SOQL (Salesforce Object Query Language): Used to query a single object or


related objects for records that match specific conditions.

o Example:

apex

CopyEdit

List<Account> accounts = [SELECT Id, Name FROM Account WHERE Name = 'Acme'];

• SOSL (Salesforce Object Search Language): Used to search across multiple


objects for specific keywords or text.
o Example:

apex

CopyEdit

List<List<SObject>> searchResults = [FIND 'Acme' IN ALL FIELDS RETURNING


Account(Id, Name), Contact(Id, Name)];

Key Difference: SOQL is used for querying a specific object or related records, while
SOSL is used for searching across multiple objects or fields.

4.8 What is Salesforce Web Services?

Salesforce Web Services allow for integration between Salesforce and external systems
via SOAP (Simple Object Access Protocol) or REST (Representational State Transfer)
APIs. These web services enable you to expose or consume data from Salesforce to
external applications or other Salesforce orgs.

• SOAP API: A robust API that supports complex data and is typically used for
enterprise-level integrations.

• REST API: A simpler, more lightweight API that is often used for mobile or web
applications.

4.9 How Do You Deploy Code into Salesforce?

Salesforce provides several methods to deploy code:

1. Change Sets: A point-and-click tool for deploying changes between Salesforce


environments (e.g., from a sandbox to production).

2. ANT Migration Tool: A command-line tool that allows for deploying and
retrieving metadata.

3. Salesforce CLI: Allows you to deploy code using scripts in a more flexible
manner, using commands like sfdx force:source:deploy.

4. IDE Tools (like Visual Studio Code): You can use the Salesforce Extensions for
VS Code to deploy code to Salesforce.

4.10 How Much Test Coverage Do You Have in Your Test Classes?
Salesforce requires at least 75% test coverage of your Apex code to deploy it to a
production environment. However, it’s best practice to aim for 100% coverage to
ensure that all scenarios and edge cases are tested.

Best Practice:

• Write test classes to cover both positive and negative test cases.

• Ensure that every line of your code is executed by your tests.

4.11 Talk About the Difference Between LC, Aura, Visualforce, and LWC

• LC (Lightning Components): A legacy framework used to create reusable UI


components with a client-server architecture. It has been replaced by LWC for
most use cases.

• Aura: A framework that allows you to build dynamic web apps for mobile and
desktop. It was the predecessor to LWC and is still in use but is less preferred for
new development.

• Visualforce: A page-based framework for building custom user interfaces with


Apex controllers. It's older than Lightning and used for more complex UI needs
that aren't covered by Lightning.

• LWC (Lightning Web Components): The modern framework for building fast,
reusable components using standard web technologies like JavaScript, HTML,
and CSS.

Key Difference:

• Aura and LC are older frameworks with a more complex architecture, while LWC
leverages modern web standards and provides a simpler, faster approach.

• Visualforce is a page-based framework for older, custom UIs, while LWC


provides the next generation of Lightning component development.

4.12 Sharing Rules in Apex

Sharing rules in Apex refer to using the Share object to programmatically grant record
access to users. For example, you can write Apex code to share records of a custom
object with specific users or groups.

Example:

apex
CopyEdit

AccountShare accShare = new AccountShare();

accShare.ParentId = accountId;

accShare.UserOrGroupId = userId;

accShare.AccessLevel = 'Read';

insert accShare;

4.13 How to Secure Credentials in Outbound?

To secure credentials in outbound integrations, Salesforce recommends storing


sensitive information like API keys, passwords, or tokens in Custom Settings, Custom
Metadata Types, or Named Credentials.

• Named Credentials: Securely stores credentials and endpoints for external


systems. It can be used to authenticate API calls without exposing credentials in
code.

Example: Create a Named Credential for an external system and then use
NamedCredential in Apex to make secure callouts.

4.14 What is Encryption in Apex?

Encryption in Apex can be implemented using Platform Encryption or custom


encryption techniques. Salesforce provides Shield Encryption for encrypting sensitive
data in transit and at rest. You can also use Apex for field-level encryption by creating
Encrypted Fields.

4.15 What is Interface in Apex?

An Interface in Apex defines a contract of methods that a class must implement. It is


used for creating polymorphic code and ensures that a class implements certain
methods, allowing for flexibility and extensibility.

Example:

apex

CopyEdit

public interface MyInterface {


void doSomething();

public class MyClass implements MyInterface {

public void doSomething() {

System.debug('Doing something');

4.16 Can an Apex Method Have Multiple Decorators?

Yes, Apex methods can have multiple decorators, but certain decorators can’t be
combined. For instance:

• You can have @InvocableMethod along with @AuraEnabled or @TestVisible.

4.17 What is Lightning Out?

Lightning Out allows you to run Lightning components outside of Salesforce, such as in
an external website or application, using a browser’s JavaScript environment.

4.18 When Do You Use RunAs in an Apex Test Class?

System.runAs() is used in test classes to simulate running code as a specific user. This
is useful when you need to test the behavior of your Apex code under different user
profiles or permission sets.

4.19 How Do You Seed Custom Metadata in a Test Class?

To seed custom metadata in a test class, you can create a new record of the custom
metadata type in the test method.

Example:

apex

CopyEdit
@isTest

public class CustomMetadataTest {

@isTest

public static void testCustomMetadata() {

MyCustomMetadata__mdt newMetadata = new MyCustomMetadata__mdt(

MasterLabel = 'TestConfig',

MyField__c = 'TestValue'

);

insert newMetadata;

4.20 How Much Percentage of Your Test Classes Use Assertions?

It's essential that test classes contain assertions to verify the expected outcomes. Aim
for 100% coverage with assertions, as they validate that your code is working correctly.

4.21 What is SOQL Injection? How Can You Prevent It?

SOQL injection occurs when malicious input is directly inserted into a SOQL query,
potentially exposing sensitive data. To prevent it, always use bind variables and avoid
concatenating strings directly into SOQL queries.

Example:

apex

CopyEdit

String userInput = 'Acme';

List<Account> accounts = [SELECT Id, Name FROM Account WHERE Name


= :userInput];

4.22 In Encryption, What is the Difference Between Probabilistic and Deterministic


Encryption?
• Probabilistic Encryption: Each encryption of the same value produces a
different ciphertext, making it more secure.

• Deterministic Encryption: The same value always encrypts to the same


ciphertext, which is useful for querying encrypted data.

4.23 Can You Encrypt a Formula Field?

No, formula fields cannot be encrypted directly. You can, however, encrypt data stored
in other fields and use it in formula fields.

4.24 Tell Three OOP Concepts

1. Encapsulation: Wrapping data and methods in a single unit, like a class, to


protect the integrity of data.

2. Inheritance: A class can inherit properties and methods from another class,
promoting reuse.

3. Polymorphism: Methods or objects can take different forms, allowing for


flexibility in code design.

4.25 What is the Sequence of Events in an Apex Trigger After Updating a Database?

1. Before Triggers: Triggered before changes are committed to the database.

2. Validation Rules: Validates data.

3. Workflow Rules, Processes, and Flows: Automation and processes are


triggered.

4. After Triggers: Triggered after changes are committed.

5. Post-Commit Logic: Such as sending emails or making callouts.

4.26 Where Would You Use Visualforce These Days? Can You Come Up with a Use
Case?

While LWC and Aura are preferred, Visualforce is still used for legacy applications or
custom UIs that require intricate designs that LWC or Aura cannot accommodate.

Use Case: A legacy app where the UI needs extensive customizations with complex
page layouts.
4.27 Have You Worked With Managed Packages? What is Managed Package?

A Managed Package is a packaged, reusable unit of code and metadata that can be
installed into Salesforce orgs. It is typically used for distributing Salesforce apps or
solutions.

4.28 What is Salesforce Security Review?

The Salesforce Security Review is a process used to assess the security of


applications or packages before they are listed on the Salesforce AppExchange.

4.29 Why Do You Need Both Triggers and Classes in Salesforce?

Triggers handle the data logic, while Apex classes implement business logic and
reusable components. Having both allows for a clean, organized structure.

4.30 Can You Test API Callouts in Apex?

Yes, you can test API callouts by using Mock callouts in test classes with the
Test.startTest() and Test.stopTest() methods, using HttpCalloutMock to simulate
responses.

4.31 What is the Difference Between a Connected and Rendered Callbacks?

• Connected Callback: Handles logic when a component is connected to the


DOM.

• Rendered Callback: Executes after the component is rendered to the screen.

4.32 How Can You Make LWC Available in a Flow?

To make an LWC available in a Flow, use the Lightning Flow Component. In the LWC
component, use the @api decorator to expose properties and methods.

Example:

javascript

CopyEdit
import { api, LightningElement } from 'lwc';

export default class MyFlowComponent extends LightningElement {

@api recordId;

// You can add more logic or methods here

5.1 What are Decorators in LWC?

Decorators in Lightning Web Components (LWC) are special annotations used to


modify the behavior of class properties or methods. They define how data is passed and
how it interacts with the framework. The most common decorators in LWC are:

• @api: Exposes a property or method to be accessible from the parent


component or to be available for other components in the DOM.

• @track: Marks a property as reactive, meaning any changes to that property will
trigger the reactivity system and update the DOM accordingly. (Note: In LWC, this
is mostly implicit, and you don't need to explicitly use @track in many cases
unless the data is an object or array.)

• @wire: Used to get data from Salesforce and makes the property or method
reactive, meaning it updates when the data changes.

• @wire (Method): Associates an Apex method to a property, making it


automatically invoked based on changes in parameters.

Example:

javascript

CopyEdit

import { api, track, wire } from 'lwc';

export default class MyComponent extends LightningElement {

@api recordId; // Exposed to parent component

@track list = []; // Reactive list


@wire(getAccounts, { recordId: '$recordId' }) accounts;

5.2 Can a LWC have multiple decorators?

Yes, a Lightning Web Component (LWC) can have multiple decorators on different
properties or methods. For example, you can use @api, @track, @wire on different
fields in the same component.

Example:

javascript

CopyEdit

import { api, track, wire } from 'lwc';

import getAccounts from '@salesforce/apex/AccountController.getAccounts';

export default class MyComponent extends LightningElement {

@api recordId; // Exposed to parent component

@track accountList = []; // Reactive property

@wire(getAccounts, { accountId: '$recordId' }) accounts;

5.3 Can you declare a constant outside of a class?

Yes, you can declare constants outside of a class in JavaScript, including in LWC, but
these constants will be scoped to the file and will not be part of the component's class.

Example:

javascript

CopyEdit

const API_URL = 'https://api.example.com';


export default class MyComponent extends LightningElement {

// Use the constant in the class

connectedCallback() {

console.log(API_URL);

However, it's more common to define constants inside the class scope if the constant is
related to the component's state or functionality.

5.4 What is the significance of the $ symbol in the parameter in LWC?

The $ symbol in LWC is used to reactively bind parameters when passing dynamic
properties to a @wire method. It tells the framework to observe changes to the property
and re-fetch data when the value changes.

For example, in the following code, $recordId will trigger the @wire method to re-run
whenever the recordId changes:

Example:

javascript

CopyEdit

import { wire, api } from 'lwc';

import getRecordDetails from '@salesforce/apex/RecordController.getRecordDetails';

export default class MyComponent extends LightningElement {

@api recordId; // This is a dynamic value

@wire(getRecordDetails, { recordId: '$recordId' }) recordData;

In this example, the $ is used to make recordId reactive. Any change in the recordId will
automatically trigger the wire service to re-fetch data.
5.5 What are the Different Lifecycle Hooks in LWC?

Lifecycle hooks in LWC are methods that are automatically called at specific points in
the component's life cycle. They allow developers to run custom logic at key moments,
such as component initialization or data updates.

Here are the lifecycle hooks:

1. constructor(): Called when the component is created, but before the


component is inserted into the DOM.

o Use it for initialization that doesn't require access to the DOM.

2. connectedCallback(): Called when the component is inserted into the DOM.

o Use it to fetch data, initialize variables, or perform setup tasks.

3. disconnectedCallback(): Called when the component is removed from the


DOM.

o Use it for cleanup, such as unsubscribing from events or clearing


intervals.

4. renderedCallback(): Called after the component's DOM has been rendered.

o Use it when you need to manipulate the DOM or perform actions that
require access to the component's rendered elements.

5. errorCallback(): Called when an error occurs during the rendering process of the
component or during the component lifecycle.

o This is useful for handling errors gracefully.

Example:

javascript

CopyEdit

export default class MyComponent extends LightningElement {

connectedCallback() {

console.log('Component inserted into the DOM');

renderedCallback() {

console.log('DOM has been rendered');


}

disconnectedCallback() {

console.log('Component removed from the DOM');

5.6 When is the Render Callback Event Called?

The renderedCallback() lifecycle hook is called after the component's DOM has been
rendered, and every time the component's reactive data changes (i.e., when properties
tracked with @track or @api are modified).

This is useful when you need to interact with the DOM directly (e.g., calling third-party
libraries that need to access elements after they have been rendered).

Example:

javascript

CopyEdit

renderedCallback() {

// This is called after the component has rendered and the DOM is available.

console.log('Component has been rendered');

5.7 What is the Difference Between Event.stopPropagation and


Event.preventDefault?

Both stopPropagation() and preventDefault() are methods on the Event object, but they
serve different purposes:

• Event.stopPropagation(): Prevents the event from bubbling up or propagating to


the parent elements. This is useful when you don’t want a parent component to
react to an event triggered in a child component.

• Event.preventDefault(): Prevents the default action of the event from


happening. For example, it stops the default behavior of a form submit or a
hyperlink click.
Example:

javascript

CopyEdit

handleClick(event) {

event.stopPropagation(); // Stop the event from propagating to parent components

event.preventDefault(); // Prevent the default action (e.g., form submission)

5.8 Why Do You Extend a Lightning Web Component?

You can extend a Lightning Web Component (LWC) if you want to reuse functionality or
make a custom component more general-purpose. You can create a base class with
shared logic, and then extend it to build specific functionality in your child components.

However, in LWC, direct inheritance of one component from another is not supported
like in Aura components. But you can extend from JavaScript base classes to share
logic.

Example:

javascript

CopyEdit

// Base class

export class BaseClass {

sharedMethod() {

console.log('Shared logic');

// In the child component

import { BaseClass } from 'c/baseClass';

export default class MyComponent extends BaseClass {


connectedCallback() {

this.sharedMethod(); // Calling method from base class

5.9 Can a LWC Component Raise and Capture the Same Event?

Yes, a Lightning Web Component (LWC) can raise and capture the same event. The
component can listen for an event, trigger it using the dispatchEvent() method, and also
handle it in the same component if necessary. Typically, events are captured by a parent
component, but you can use CustomEvent to allow both raising and handling events in
the same component.

Example:

javascript

CopyEdit

// In the same component

handleClick() {

// Raise an event

const event = new CustomEvent('myevent', { detail: 'data' });

this.dispatchEvent(event);

connectedCallback() {

// Capture the event

this.addEventListener('myevent', this.handleEvent);

handleEvent(event) {

console.log('Event captured with data:', event.detail);

}
5.10 What is the Difference Between var, let, and const?

These are three different ways to declare variables in JavaScript, with distinct behaviors
regarding scope and mutability:

• var: Function-scoped or globally-scoped, allowing redeclaration and re-


assignment. It is hoisted to the top of its scope.

Example:

javascript

CopyEdit

var a = 1;

if (true) {

var a = 2; // Same variable, overwritten.

console.log(a); // Outputs 2

• let: Block-scoped and allows re-assignment but not redeclaration within the
same block.

Example:

javascript

CopyEdit

let a = 1;

if (true) {

let a = 2; // Different variable inside the block.

console.log(a); // Outputs 2

console.log(a); // Outputs 1

• const: Block-scoped and immutable (cannot be reassigned), but the contents


of objects or arrays can still be modified.

Example:

javascript
CopyEdit

const a = 1;

a = 2; // Error: Assignment to constant variable.

const obj = { prop: 1 };

obj.prop = 2; // Allowed, as object contents can be modified.

5.11 How to Communicate Between a Parent and a Child LWC?

Communication between a parent and child Lightning Web Component (LWC) is done
using properties and events:

1. Parent to Child: The parent can pass data to the child using public properties
marked with @api.

2. Child to Parent: The child can communicate with the parent using Custom
Events.

Example of Parent to Child:

html

CopyEdit

<!-- Parent Component -->

<c-child-component record-id="123" message="Hello"></c-child-component>

Example of Child to Parent:

javascript

CopyEdit

// Child Component

const event = new CustomEvent('message', { detail: 'Message from child' });

this.dispatchEvent(event);

Example of Parent handling Child Event:

html

CopyEdit

<!-- Parent Component -->


<c-child-component onmessage={handleMessage}></c-child-component>

javascript

CopyEdit

// Parent Component JS

handleMessage(event) {

console.log('Message from child: ' + event.detail);

You might also like