Salesforce Developer Interview Questions and Answers


 Hi there, if you are reading this blog then I believe you are planning for your next Salesforce Developer Interview or maybe you just want to enhance your knowledge based on the interview questions being asked in the dev interviews.

The questions below are based on my knowledge and understanding of the salesforce ecosystem, and feedback collected from a small group of salesforce devs.

Still before attempting any interview my suggestion would be to have proper knowledge and don't rely only on the interview questions. This is just to give you an idea about the questions/scenarios that you may face in your interview.

All the best !

1. What are the differences between Before and After triggers in Salesforce?

Answer:

Before Triggers: These triggers are used to validate or update records before they are saved to the database. They are typically used to perform validation checks or modify a record's values before they are committed.

After Triggers: These triggers are executed after records have been saved to the database. They are used when you need to access the record’s ID or perform operations that require the record to be committed to the database, such as making a callout or updating related records.


2. How can you enforce field-level security in Apex?

Answer:

In Apex, field-level security can be enforced by using Schema.DescribeSObjectResult and Schema.DescribeFieldResult methods to check the user's access to a particular field. The isAccessible(), isCreateable(), isUpdateable() methods can be used to verify if the user has the necessary permissions before performing DML operations.

1
2
3
4
5
if (Schema.SObjectType.Account.fields.AccountNumber.isAccessible()) {

    // Perform operation

}


3. Explain the purpose of the @isTest annotation in Apex.

Answer:

The @isTest annotation is used to define classes and methods that only contain test code. It tells Salesforce that the annotated class or method is meant for testing purposes. Code marked with @isTest is not counted against your organization’s code size limit. Additionally, such methods are not executed in production.


4. What are the different governor limits in Salesforce?

Answer:

Salesforce enforces governor limits to ensure efficient use of resources on the multi-tenant platform. Some key governor limits include:

  • SOQL Queries: Maximum 100 queries in a synchronous transaction.
  • DML Statements: Maximum 150 DML operations in a transaction.
  • Heap Size: Maximum 6 MB for synchronous Apex, 12 MB for asynchronous.
  • CPU Time: Maximum 10 seconds for synchronous, 60 seconds for asynchronous transactions.
  • Callouts: Maximum of 100 callouts in a transaction.


5. How do you handle asynchronous processing in Salesforce?

Answer:

Asynchronous processing in Salesforce can be handled using:

  • Future Methods: For executing long-running operations like callouts without blocking the main thread.
  • Batch Apex: For processing large volumes of data, batch jobs can be broken into manageable chunks.
  • Queueable Apex: Offers more complex asynchronous processing with the ability to chain jobs.
  • Scheduled Apex: Allows execution of Apex code at a specific time.


6. What are custom settings and how do you use them?

Answer:

Custom settings are similar to custom objects and are used to store static data that doesn’t change frequently. There are two types:

  • List Custom Settings: Allow you to create a list of records.
  • Hierarchy Custom Settings: Allow you to define settings at different levels (org-wide, profile, or user).

Custom settings are accessed using CustomSettingName__c.getInstance() for hierarchy and CustomSettingName__c.getAll() for list settings.


7. How does Salesforce handle data sharing and visibility?

Answer:

Salesforce handles data sharing and visibility through several mechanisms:

  • Organization-Wide Defaults (OWD): Set the baseline level of access to records for users in your organization.
  • Role Hierarchies: Grant access to records based on the user’s role within the hierarchy.
  • Sharing Rules: Extend access to users based on record ownership or criteria.
  • Manual Sharing: Allows individual users to manually share records with others.
  • Apex Managed Sharing: Allows developers to programmatically share records with specific users or groups.


8. What are the best practices for writing triggers in Salesforce?

Answer:

Best practices for writing triggers include:

  • One Trigger Per Object: To avoid logic duplication and ensure proper order of execution.
  • Use of Handler Classes: Separate business logic into handler classes to make triggers more modular and testable.
  • Bulkify Your Code: Ensure that your trigger can handle multiple records by using collections.
  • Avoid SOQL/DML in Loops: To prevent hitting governor limits, move SOQL queries and DML operations outside loops.
  • Handle Recursion: Use static variables to prevent recursive trigger execution.


9. What is a Map in Apex and how is it used?

Answer:

A Map is a collection type in Apex that holds key-value pairs. It is useful for quick lookups of data based on a unique key. Maps are particularly efficient when querying records that need to be matched with other records or used in a loop.

Example:

1
Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Id, Name FROM Account]);

This example creates a map where the key is the account ID and the value is the account record.


10. How do you use SOQL and SOSL in Salesforce?

Answer:

SOQL (Salesforce Object Query Language): Used to query records from a single object or multiple objects that are related to each other. It's similar to SQL.

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


SOSL (Salesforce Object Search Language): Used to search text across multiple objects simultaneously. It returns records that match the search criteria.

List<List<SObject>> searchResults = [FIND 'Acme*' IN ALL FIELDS RETURNING Account(Id, Name)];


11. What are the different types of relationships in Salesforce?

Answer:

  • Lookup Relationship: A loosely coupled relationship between two objects. It’s used when the objects can exist independently.
  • Master-Detail Relationship: A tightly coupled relationship where the detail (child) object is dependent on the master (parent) object.
  • Many-to-Many Relationship: Achieved through a junction object that has two master-detail relationships with the objects being related.


12. Explain the use of Schema.describeSObjects() in Apex.

Answer: Schema.describeSObjects() is a method used to retrieve metadata about one or more sObjects, such as their fields, record types, and relationships. It allows you to dynamically interact with different sObjects without hardcoding their metadata.

Example:

1
2
3
Schema.DescribeSObjectResult accountDescribe = Account.sObjectType.getDescribe();

Map<String, Schema.SObjectField> fields = accountDescribe.fields.getMap();


This code retrieves the metadata for the Account object and stores its fields in a map.


13. What is a Dynamic SOQL query?

Answer: Dynamic SOQL refers to building SOQL queries at runtime using Apex code. This allows you to construct and execute queries based on variable inputs.

Example:

1
2
3
String queryString = 'SELECT Id, Name FROM Account WHERE Name = :accountName';

List<Account> results = Database.query(queryString);


This method is useful when the query structure isn't known until runtime.


14. How do you prevent SOQL injection in Salesforce?

Answer: SOQL injection can be prevented by:

Using Bind Variables: Instead of concatenating strings, use bind variables in your queries.

Sanitizing User Input: Ensure that any user inputs used in queries are validated and sanitized.

Example:

1
2
3
4
5
String userInput = 'Acme';

String query = 'SELECT Id, Name FROM Account WHERE Name = :userInput';

List<Account> accounts = Database.query(query);


Bind variables prevent SOQL injection by safely inserting user-provided values into the query.


15. What is ApexPages.currentPage() used for?

Answer: ApexPages.currentPage() is a method in Visualforce that returns the current page context. It provides access to various elements of the page, such as parameters, URL, and state.

Example:

1
String recordId = ApexPages.currentPage().getParameters().get('id');

This retrieves the ID parameter from the URL of the current page.


16. When to use Flow vs Trigger?

Answer:

Flows are great for less complex scenarios and can be managed by administrators or low-code developers.

Triggers are suited for complex scenarios that require greater control over the execution context and business logic, and they require coding skills to manage.

Choosing between Flows and Triggers depends on the specific use case, the complexity of the logic, and the development skills available in your Salesforce team.


17. How do you manage recursive triggers in Salesforce?

Answer: Recursive triggers can cause infinite loops and should be managed using static variables to ensure that the trigger logic only runs once per transaction.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public class AccountTriggerHandler {

    public static Boolean isTriggerExecuted = false;

    

    public static void handleBeforeUpdate(List<Account> newList) {

        if(!isTriggerExecuted) {

            isTriggerExecuted = true;

            // Trigger logic

        }

    }

}

This prevents the trigger from running multiple times during the same transaction.


18. What is a Governor Limit in Salesforce?

Answer: Governor limits are Salesforce-enforced limits to ensure efficient use of resources in a multi-tenant environment. These limits include restrictions on the number of SOQL queries, DML operations, and CPU time a single transaction can use. Developers must design their code to stay within these limits to avoid runtime errors.


19. What is the difference between System.runAs() and normal user context?

Answer: System.runAs() allows you to execute code in the context of a specified user, which is useful for testing scenarios where you need to simulate a user with different permissions or profiles. Normal execution context runs in the context of the user logged in at the time.

1
2
3
4
5
6
7
User user = [SELECT Id FROM User WHERE Username='testuser@example.com'];

System.runAs(user) {

    // Code executed as the specified user

}


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

Answer: The @future annotation is used to mark methods for asynchronous execution. This allows long-running operations, like callouts, to be executed in the background without blocking the main thread.

1
2
3
4
5
6
7
@future

public static void calloutToExternalService() {

    // HTTP callout code here

}


Use @future for operations that do not need to return a result immediately.


21. What is Batch Apex and when would you use it?

Answer: Batch Apex is used to process large volumes of data in smaller chunks, allowing you to bypass governor limits that apply to normal synchronous transactions. It's ideal for operations like processing thousands of records or making large-scale updates.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
global class MyBatchClass implements Database.Batchable<SObject> {

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

        return Database.getQueryLocator('SELECT Id FROM Account');

    }

    

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

        // Batch processing logic here

    }

    

    global void finish(Database.BatchableContext bc) {

        // Final actions

    }

}



22. What are Apex sharing reasons?

Answer: Apex sharing reasons allow developers to define why a record was shared with a user or group. This is useful for creating custom sharing rules that can be referenced and maintained more easily in code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
AccountShare accountShr = new AccountShare();

accountShr.AccountId = accountId;

accountShr.UserOrGroupId = userId;

accountShr.AccessLevel = 'Read';

accountShr.RowCause = Schema.AccountShare.RowCause.Manual;

insert accountShr;


This example creates a manual sharing rule for an account.



23. How does Salesforce handle Exception Handling in Apex?

Answer: Salesforce provides try-catch blocks to handle exceptions in Apex. You can catch specific exceptions or a generic Exception to handle unexpected errors gracefully.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
try {

    // Code that might cause an exception

} catch (DmlException e) {

    // Handle DML exceptions

} catch (Exception e) {

    // Handle other exceptions

} finally {

    // Code that runs regardless of whether an exception was thrown

}


This helps in preventing the application from crashing and allows you to log or handle errors appropriately.


24. What is Database.Stateful in Batch Apex?

Answer: Implementing Database.Stateful in a batch class allows the class to retain state between the execution of batch chunks. This is useful for keeping track of stateful information like counters, lists, or collections across batch executions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
global class MyBatchClass implements Database.Batchable<SObject>, Database.Stateful {

    public Integer recordsProcessed = 0;

    

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

        recordsProcessed += scope.size();

        // Processing logic

    }

}



25. How do you debug a Flow vs Trigger?

Answer: 

Flows:

Easier to debug with the built-in debugging tools in Flow Builder, which allows for step-by-step execution and provides detailed error messages.

No need for deployment; changes can be activated directly in the sandbox or production.


Triggers:

Debugging can be more challenging as it requires using Developer Console logs or Apex test classes.

Error handling must be explicitly written in the code (try-catch blocks) to manage exceptions.



26. What are the different ways to implement Custom Exceptions in Apex?

Answer: You can define custom exceptions by extending the Exception class in Apex. Custom exceptions allow you to create specific error-handling routines tailored to your application’s logic.

public class MyCustomException extends Exception {}

Then, you can throw and catch this exception within your code:

1
2
3
4
5
if (someCondition) {

    throw new MyCustomException('Custom error message');

}


27. How do you handle JSON in Apex?

Answer: Apex provides JSON class methods to serialize and deserialize JSON strings. This is essential for integrating with external systems that use JSON data formats.

1
2
3
4
5
6
7
8
9
// Serialize Apex object to JSON

String jsonString = JSON.serialize(someApexObject);



// Deserialize JSON to Apex object

MyClass obj = (MyClass) JSON.deserialize(jsonString, MyClass.class);


This allows seamless data exchange between Salesforce and other platforms.


28. What is Test.startTest() and Test.stopTest() used for in Apex testing?

Answer: Test.startTest() and Test.stopTest() are used in Apex test methods to reset governor limits and execute code in a fresh context. This is useful for testing scenarios where you need to ensure that your code doesn’t exceed governor limits.

1
2
3
4
5
Test.startTest();

// Test code that needs fresh governor limits

Test.stopTest();


These methods are especially useful when testing asynchronous code like @future methods.


29. How do you use Platform Events in Salesforce?

Answer: Platform Events are used for event-driven architecture in Salesforce, allowing decoupled communication between various components of the system. You define a platform event object and publish events from Apex, which can then be consumed by triggers, processes, or external systems.

1
2
3
MyPlatformEvent__e event = new MyPlatformEvent__e(Field1__c='Value');

Database.SaveResult sr = EventBus.publish(event);


Platform events are ideal for real-time integration scenarios.


30. What are Custom Labels and how are they used?

Answer: Custom Labels are used to create multilingual text values that can be used in Apex classes, Visualforce pages, or Lightning components. They help in managing localization and user-facing text.


String labelValue = System.Label.MyCustomLabel;


This fetches the value of the custom label, which can vary depending on the user's language settings.


31. What performance consideration you should be aware of while using Flow or Trigger in Salesforce?

Answer: 

Flows:

  • Easier to manage in terms of governor limits since they are declarative.
  • May consume more CPU time for complex operations due to their point-and-click nature.
  • Can sometimes perform slower than Triggers when handling large data volumes.


Triggers:

  • More efficient for handling bulk data operations as they can be explicitly optimized with Apex.
  • Developers have more control over the performance of triggers by using best practices like bulkification and avoiding SOQL queries within loops.



32. How do you manage Field History Tracking in Salesforce?

Answer: Field History Tracking allows Salesforce to track changes to fields on standard and custom objects. When enabled, Salesforce automatically logs changes to the specified fields, including old and new values.

You enable field history tracking in the object's settings and can access the tracked data using History related lists or by querying the History objects in SOQL.


33. What is the difference between Public Groups and Roles?

Answer:

Roles: Define a hierarchy that controls record access across the organization. Each user is assigned a role, which dictates their access to records.

Public Groups: Collections of users, roles, and other public groups. Public Groups are used to simplify the sharing of records and permissions.

Roles are primarily used for defining data access, while Public Groups are used for sharing rules, manual sharing, and as a way to group users for security and data sharing purposes.


34. Explain the use of Lightning Data Service (LDS) in Lightning Components.

Answer: Lightning Data Service (LDS) provides a way to interact with Salesforce data without writing Apex code. It is similar to Visualforce standard controllers but for Lightning Components. LDS handles CRUD operations, caching, and sharing automatically, reducing the need for custom Apex controllers.

Example:

1
2
3
4
5
<lightning:recordForm
    objectApiName="Account"
    recordId="{!v.recordId}"
    layoutType="Full"
    mode="View"/>


This provides a form for viewing an Account record using LDS.


35. What is Einstein Bots and how are they used in Salesforce?

Answer: Einstein Bots are AI-powered chatbots integrated into Salesforce that help automate and streamline customer interactions. They can handle common customer service queries, provide information, and escalate issues to live agents as needed.

Einstein Bots are configured within the Service Cloud and can be customized using predefined rules, intents, and dialog flows.


36. What is Visualforce and when would you use it?

Answer: Visualforce is a framework that allows developers to build custom user interfaces in Salesforce. It is composed of HTML, Apex, and various Salesforce-specific tags and components.

Visualforce is typically used when you need to create custom pages that require more flexibility than standard page layouts provide, such as when integrating third-party services or creating complex forms.


37. What are Record Types and how are they used?

Answer: Record Types in Salesforce allow you to define different business processes, picklist values, and page layouts for different users or profiles. They are commonly used when a single object is used for multiple purposes within an organization.

For example, you might use Record Types to differentiate between business accounts and individual accounts, each with different fields and processes.


38. What is the Schema class in Apex?

Answer: The Schema class provides methods for schema metadata, such as information about sObjects, fields, and relationships. It’s commonly used for dynamic programming scenarios.

Example:

1
2
3
Schema.DescribeSObjectResult result = Account.sObjectType.getDescribe();

Map<String, Schema.SObjectField> fields = result.fields.getMap();


This retrieves metadata about the Account object and its fields.


39. How do you handle bulk data operations in Salesforce?

Answer: Bulk data operations are handled using Bulk API or through Bulkified Apex code. Bulkification refers to the process of ensuring that your code can handle multiple records at once, typically by using collections like lists, maps, and sets.

This approach ensures that you stay within governor limits and can handle large volumes of data efficiently.


40. What is Continuous Integration (CI) in Salesforce development?

Answer: Continuous Integration (CI) is the practice of automatically building and testing your code every time a change is committed to version control. In Salesforce, CI involves automated deployment processes, testing, and validation using tools like Jenkins, Git, and Salesforce DX.

CI helps in maintaining code quality and ensures that changes do not break the existing functionality.


41. What is Salesforce DX and how does it help in development?

Answer: Salesforce DX (Developer Experience) is a set of tools and practices designed to improve the development lifecycle on the Salesforce platform. It includes features like scratch orgs, source-driven development, and integration with version control systems.

Salesforce DX enables developers to work in a more agile and collaborative environment, promoting best practices in modern software development.


42. Explain the concept of Permission Sets in Salesforce.

Answer: Permission Sets in Salesforce are collections of settings and permissions that can be assigned to users to grant additional access beyond their profile. They are used to extend access without modifying the user's profile.

For example, if a user needs access to a specific object or permission temporarily, you can assign them a permission set instead of creating a new profile.


43. How does Salesforce handle Record Locking?

Answer: Record locking in Salesforce occurs when a record is being edited by one user and another user attempts to edit it simultaneously. Salesforce uses implicit locking to prevent conflicts. Developers can also use explicit locking in code with FOR UPDATE in SOQL queries to lock records and prevent other transactions from modifying them until the lock is released.


44. What is Static Resource in Salesforce?

Answer: Static Resources in Salesforce allow you to upload files like images, CSS, JavaScript, and other content that can be referenced in your Visualforce pages, Lightning components, or apps. They are cached for performance and can be managed via the Salesforce UI.

<apex:stylesheet value="{!$Resource.myStyles}"/>


This example references a CSS file uploaded as a static resource.


45. How do you create Reusable Lightning Components?

Answer: Reusable Lightning Components are built by creating components that accept attributes and handle events. These components can be used across different applications, pages, and contexts.

Example of a reusable button component:

1
2
3
4
5
6
7
<aura:component>

    <aura:attribute name="label" type="String" required="true"/>

    <lightning:button label="{!v.label}" onclick="{!c.handleClick}"/>

</aura:component>


This button component can be reused wherever a button with customizable text is needed.


46. What is Cross-Object Formula in Salesforce?

Answer: Cross-Object Formulas in Salesforce allow you to reference fields from parent objects in a formula field on a child object. This is useful for displaying related data without creating additional fields or relationships.

Example:

ParentObject__r.FieldName__c


This formula fetches the value from the parent object’s field and displays it on the child object.


47. What is Shield Platform Encryption?

Answer: Shield Platform Encryption in Salesforce is a feature that provides encryption at rest for sensitive data, allowing organizations to comply with regulations and internal policies. It encrypts fields, files, and attachments without requiring code changes, and integrates seamlessly with the Salesforce platform.


48. What is the difference between Database.insert() and insert in Apex?

Answer: 

insert: Performs DML operations and throws an exception if any error occurs, rolling back all changes.

Database.insert(): Allows partial success and returns a Database.SaveResult object that provides details on success or failure for each record. It also has an allOrNone parameter to control rollback behavior.


49. What is a Custom Metadata Type, and how is it different from Custom Settings?

Answer: 

Custom Metadata Types: Used to store configuration and metadata, which can be deployed between environments using change sets or metadata API. They are similar to custom objects but are mainly used for configurations.

Custom Settings: Used to store custom data sets that are frequently accessed and do not change often. They are not easily deployable between environments and are more for user- or application-specific settings.


50. Explain the use of System.runAs() for testing different user permissions.

Answer: System.runAs() is used in test methods to execute code in the context of a different user. This is useful for testing how your application behaves for users with different profiles, roles, or permission sets.

1
2
3
4
5
System.runAs(new User(Id='005B0000001MlHk')) {

    // Code executed with different user permissions

}


This helps ensure that your code works correctly under different user scenarios.


Note: The purpose of sharing above questions & answers are to give you an idea about how it is going to be during interviews. Please don't rely on it and go with proper preparation.






 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

2 Comments

  1. Hi Kapil, Thankyou for the Blog. Its detailed and informative.Can you do one on omnitoolkit or Big Objects ?.its a less discussed topics and i cant find anything outside salesforce documentation.

    ReplyDelete
    Replies
    1. Hi there, thanks glad you like the blog. I will try to sync with few omnistudio developers and collect their inputs to create it.

      Delete