Salesforce Interview Questions

Triggers:

You can perform the custom action by using triggers before or after DML operations happen in salesforce,

Insertions, updates, or deletions. Just like database systems support triggers, apex provides trigger support for managing records.

Typically, you use triggers to perform operations based on specific conditions, to modify related records or restrict certain operations from happening. You can use triggers to do anything you can do in Apex, including executing SOQL and DML or calling custom Apex methods.

Use triggers to perform tasks that can’t be done by using the point-and-click tools in the Salesforce user interface. For example, if validating a field value or updating a field on a record, use validation rules and workflow rules instead.

Triggers can be defined for top-level standard objects, such as Account or Contact, custom objects, and some standard child objects. Triggers are active by default when created. Salesforce automatically fires active triggers when the specified database events occur.

Trigger Events:

Before insert after insert, before update, after update , before delete, after delete, after undelete

Trigger Context variables:

formation we use trigger context variables.

Below context variables will return either true or false.

  1. isBefore (returns true if the trigger context is Before Mode)
  2. isAfter (returns true if the trigger context is After Mode)
  3. isInsert (returns true if the trigger context is Insert)
  4. isUpdate (returns true if the trigger context is Update)
  5. isDelete (returns true if the trigger context is Delete)
  6. isUndelete (returns true if the trigger context is Undelete)
  7. isExecuting (returns true if the apex class method is getting call from Apex Trigger)

Below context variables will store records at runtime.

  1. old (stores history (old versions) of the records.)
  2. oldMap (stores history (old versions) of the records along with id.)
  3. new (stores new version of the records.)
  4. newMap (stores new version of the records along with id.)
  5. Read/Write access over the trigger collections on different events –
Events trigger.old trigger.oldMap trigger.new trigger.newMap
before insert NA NA Read/Write NA
after insert NA NA Read Only Read Only
before update Read Only Read Only Read/Write Read Only
after update Read Only Read Only Read Only Read Only
before delete Read Only Read Only Read Only Read Only
after delete Read Only Read Only Read Only Read Only
after undelete Read Only Read Only Read Only Read Only

 

 When to use before triggers and when to use after triggers?

Before Triggers

  1. To perform the validations we should use before triggers.
  2. If you are updating any field on the same object on which you are writing the trigger and no need to explicitly include the DML statemetns (already due to DML operation only trigger fire and it is still in progress at this point of time.)

After Triggers

  1. If you are dealing with relationship records and if you need record id in these situations we should use after trigger (in before insert record doesn’t contain the record id).

For the same event if there are multiple triggers on the object, how to control the order of execution?

We cannot control the order of execution in this situation. It is recommended to have only one trigger per one object.

Note: We can keep the logic of the apex trigger in an apex class and can invoke from that class.

What are the recursive triggers and how to avoid?

If we perform update operation on the record in after update event logic recursive triggers will arise. Using static boolean variable in an apex class (we should not keep static boolean variable inside of the trigger) we can avoid recursive triggers.

What is MIXED-DML-OPERATION error and how to avoid?

If we perform DML operation on standard/custom object and global objects(User, UserRole, Group, GroupMember, Permission Set, etc…) in same transaction this error will come. To avoid this error, we should perform DML operation on standard/custom object records in a different transaction. In general all the apex classes and apex triggers execute synchronously (execute immediately).

if we perform DML operation on standard/custom object records asynchronously (execute in future context), we can avoid MIXED-DML-OPERATION error.

To execute logic asynchronously keep the logic in an apex method (in a separate apex class, not in same apex trigger) which is decorated with @future annotation.

see the below example –

Note: To analyse the code copy it and paste it in notepad for the convenience.

public class TriggerUtility {  /*

  1. Following future method execute asynchronously (whenever server is free it will execute in future context).
  2. We should not declare @future method in Apex Trigger.
  3. @future method should be always static.
  4. @future method accepts only primitive data types (Integer, String, Boolean, Date, etc…) as parameters and it won’t accept

non-primitive data types (sObject,Custom Objects and standard Objects etc.. ) as parameters.

  1. @future method should not contain return type. Always it should be void.
  2. From an apex trigger we can make only make asynchronous call outs. To make call out we should include “callout = true” beside the future @annotation.
  3. We cannot perform synchronous call outs from Apex Trigger.

*/

//Below is the example for the future method –

@future(callout = true)

public static void processAsync(primitive parameters) {

//Logic to insert/update the standard/custom object.

}

}

 

  1. What is the order of execution in salesforce?

We are creating validation rules, workflow rules, assignment rules, auto-responsive rules, escalation ruels and apex triggers etc..

If the condition is same for all the rules which will execute first and which will execute next, for this salesforce provide the order.

Order of execution in salesforce – Order of execution in Salesforce:

  1. Prepare the record for insert/update operation.
  2. It will replace all the old field values with new field values.
  3. If the request is coming form UI all the system validations will execute –
    • DataType
    • Length
    • Required
    • unique
    • pageLayot level validations
  4. before triggers
  5. Custom Validations and again system validation rules will fire (pageLayot level validations won’t fire at this point of time).
  6. record will be saved into the database but doesn’t not commit.
  7. after triggers.
  8. assignment rules.
  9. auto-responsive rules.
  10. Workflow Rules
  11. incase of Workflow Rule Field updates again before triggers and after triggers fire one more time. System validation ruels for duplicate chcek.
  12. Escalatoin Rules.
  13. Rollup-Summary fields will be calculated.
  14. Grant parent Rollup-Summary fields will be calculated.
  15. Criteria base sharing evaluation.
  16. Record will be commited into the database.
  17. Post Commit logic (Sending emails).

There is a validation rule which will fire if amount = 100 and will display the error message. There is a workflow rule which will fire if amount > 100 and will update amount field to 100. One of user saved the record by giving value as 1000.
what will the value of the amount field.

Validation rules will fire first then workflow rules will fire. So, the answer is 100 (Even though there is a validation rule because of the workflow rule it will accept 100 in the amount field).

There is a before trigger which will fire if amount = 100 and will display the error message. There is a workflow rule which will fire if amount > 100 and will update amount field to 100. One of user saved the record by giving value as 1000.
what will the value of the amount field.

It will throw the validation error because after the workflow field update before triggers fire one more time.

TEST Classes:

 What is the purpose of writing the test class?

After developing an apex class or apex trigger we should write the unit tests and ensure that we are able to execute at least 75% of the lines of code. If you are moving the code from sandbox to sandbox regarding code coverage you won’t face any issue.

If you are moving the code from sandbox to production, you need to include all the test classes at the time of deployment and salesforce will run all the test classes which you included for the deployment as well as test classes which are already present in production, if the code coverage is less than 75%deployment will fail.

Is it possible to write test code inside of an apex class or apex trigger?

we cannot write test code (test methods) inside of the apex trigger.

From API Version 28.0, we cannot write the test methods inside of an apex class which is not decorated with @isTest.

We can write test methods only in a class which is decorated with @isTest.

Note: We have a governor limit for the overall Apex Code size of the organization which is of 3 MB. If we decorate a class with @isTest annotation Apex Code Size governor limit will be bypassed.

What is the purpose of seeAllData?

By default test class cannot recognize the existing data in the database.

if you mention @isTest(seeAllData = true) then test class can recognize the existing data in the database.

See the below examples –

  • From a List Custom Settings we cannot fetch the existing data without seeAllData = true in test class.
  • Suppose you have a custom object called ‘CustomObject__c’ and it contains many records, we cannot fetch the existing data without seeAllData = true in test class.

Note: It is not recommended to use seeAllData = true for a test class. Based on the existing data in database code coverage will impact.

What is the purpose of Test.startTest() and Test.stopTest()?

Test.startTest() and Test.stopTest() maintains fresh set of governor limits. Assume that you are consuming 99 SOQL queries outside of Test.startTest() and Test.stopTest() then if you include any SOQL inside of Test.startTest() and Test.stopTest() count will start from 1.

Per testMethod we can use Test.startTest() and Test.stopTest() only for one time.

To execute asynchronous methods synchronously we can call those methods from inside of Test.startTest() and Test.stopTest().

What is the purpose of system.runAs()?

By default test class runs in System Mode. If you want to execute a piece of code in a certain user context then we can use system.runAs(UserInstance). For more details refer 2nd question in visualforce category.

To avoid MIXED-DML-OPERATION error we can include DML statements inside of system.runAs(), still the error persists keep DML statements inside of Test.startTest() and Test.stopTest().

What are the assert statements?  What is the purpose?

To compare Actual value and Expected value we use assert statements.

Types of assert statements

  1. system.assertEquals(val1,val2): If both val1 and val2 are same then test class run successfully otherwise test class will fail.
  2. system.assertNotEquals(val1,val2): If both val1 and val2 are not same then test class run successfully otherwise test class will fail.
  3. system.assertEquals(val1> val2): If the condition satisfied then test class run successfully otherwise test class will fail.

What is the purpose of Test.isRunningTest()?

Sometimes we cannot satisfy certain if conditions for the apex classes, in those situations on those if conditions we can add Test.isRunningTest separated with or condition. Example: if(condition || Test.isRunningTest())

 What is the purpose of @TestVisible?

Sometimes in test classes we need to access a variable from Apex Class, if it is private we cannot access for that we will replace private with public. for this reason we are compromising the security. To avoid this before the private variables in apex class we can include @TestVisible so that even though variable is private we can access from the test class.

 What are the test class best approaches?

  1. We should not depend on the existing data in the database. We should create the test data for all the possible scenarios. Note: Profiles and recordTypes cannot be created programmatically, we can query from the database. For the remaining objects including users we should create the test data.
  2. While testing apex triggers and batch classes, we should do bulk testing at least with 200 records.
  3. We should test for all the positive and negative scenarios.

What are the types of Web Services?

Following are the different types of web services –

SOAP API –

  • SOAP: Simple Object Access Protocol
  • API: Application Programming Interface
  • SOAP API web services are available from long term.
  • SOAP protocol is used for the communication between the platforms.
  • Information exchange will happen with ‘WSDL’.
  • WSDL: Web service Description Language
  • Default data exchange format is XML (used to exchange data in webservices)

REST API –

  • REST: Representational State Transfer
  • REST API web services are available from last 10 years. Now a days most of the implementations are happening with REST API
  • Http protocol/SOAP protocol is used for the communication between the platforms(mostly http protocols will be used).
  • No concept of ‘WSDL’ in REST API. Information will be appended to endpoint URL
  • Default data exchange format is JSON. XML format also can be used.
  • JSON: JavaScript Object Notation
  • JSON is light weight and easy to parse the data when compared with XML.

What are the types of Collections available in Apex?

List (ordered and allow duplicates)

Set (unordered and won’t allow duplicates)

Map (Key and value pair)

What is the difference between List and Set ?

List Set
List is Ordered. Set is unordered.
List allows duplicates. Set doesn’t allow duplicates.
We can access list elements with index. Set elements cannot be accessed with index.
We can sort list elements with sortmethod (default sorting order is ascending). sort method is not available for Set.
Contains method is not available in List. Contains method is available for Set to search for a particular element in the set.
We can process records which are stored in list using DML statements(insert, update, delete and undelete). We cannot process recordswhich are stored in set usingDML statements.

What is the maximum size of the list?

No limit for the size of a list. It only depends on the heap size which is 6 MB (Synchronous) and 12 MB (Asynchronous).

 What are the map methods available in Apex?

//Map holds key and value pair.

//Syntax: Map mapName = new Map();

/*Map countryISTCodeMap = new Map();

countryISTCodeMap.put(‘India’,’91’);

countryISTCodeMap.put(‘USA’,’001′);

countryISTCodeMap.put(‘India’,’911′);//replaces old value with new value.*/

Map countryISTCodeMap = new Map{‘India’=>’91’,’USA’=>’001′, ‘India’=>’911’};

system.debug(‘countryISTCodeMap result: ‘+countryISTCodeMap+’ with size ‘+countryISTCodeMap.size());

system.debug(‘countryISTCodeMap keys: ‘+countryISTCodeMap.keyset());

system.debug(‘countryISTCodeMap values: ‘+countryISTCodeMap.values());

system.debug(‘countryISTCodeMap search: ‘+countryISTCodeMap.containsKey(‘India’));

system.debug(‘countryISTCodeMap fetching value based on key: ‘+countryISTCodeMap.get(‘India’));

//map keys are case-sensitive.

  1. keyset(): To fetch only keys from the map.
  2. values(): To fetch only values from the map.
  3. containsKey(value): To search a key from the map.
  4. get(key): By supplying the key we can fetch the value.
  5. put(key,value): To add key and value in a map.

 

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s