Tag

Slider

Browsing

81. How to use @future Annotation in Apex?

Future method is used to run the process in a separate thread at a later point of time(when resources are available). For example, you can use the future annotation when making an asynchronous Web service callout to an external service. Without the annotation, the Web service callout is made from the same thread that is executing the Apex code, and no additional processing can occur until the callout is complete (synchronous processing).

global class MyFutureClass {

@future static void myMethod(String a, Integer i)

{

System.debug(‘Method called with: ‘ + a + ‘ and ‘ + i);

// Perform long-running code

}

}

82. What are the different considerations while implementing future method?

  • Remember that any method using the future annotation requires special consideration because the method does not necessarily execute in the same order it is called.
  • Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or setMethodName methods, nor in the constructor.
  • You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call a trigger from an annotated method that calls another annotated method.

83. When do we use Batch Apex?

When we have large volumes of data and do not require business logic to be processed in realtime we can use or implement Batch apex. We can process upto 50 million records using Batch Apex.

84. What are the different methods in Batch Apex?

Batch apex runs in Asynchronous mode and consists of 3 methods.

Start – Start method is used to query the list of records

Execute – Execute method is used to process business logic

Finish – Finish method is used to send email or call a different batch job or do nothing.

85. What is the purpose of QueryLocator in Batch Apex?

Query locator is used in Start method of Batch apex and it gives the ability to process upto 50 million records.

86. What are the different types of interfaces used in Batch Apex?

There are 3 different interfaces in Batch Apex

1. Database.Batchable

2. Schedulable

87. What is batch job chaining?

We can launch other Batchjob from finish method of the first job. This is called batch job chaining.

88. How many batch jobs can be run in parallel?

We can run a maximum of 5 batch jobs parallelly.

89. How many batch jobs can be in Apex flex queued at any given point of time?

With the Apex flex queue, you can submit up to 100 batch jobs.

90. How can we invoke batch job from Developer console?

Example: We have a batch job AccountProcessBatch that needs to be executed with a default size. Then we can use the below command.

Database.executebatch(new AccountprocessBatch());

Dev Tip 3: Execute Batchjob from Anonymous Window/Dev Console

71. What is the difference between public class vs Global class?

Public – Public class is accessible only in the corresponding namespace

Global – Global Class is accessible across the Salesforce instance irrespective of namespaces.

72. What are different access modifiers in Apex?

public/private/global

73. What is difference between with Sharing vs without Sharing?

Any class that has With Sharing will enforce the Sharing rules for the current user.

Any class that has without sharing specified or no sharing specified then it runs in the context of system admin mode/system mode.

Dev Tip 7: Difference between With Sharing and Without Sharing in Salesforce

74. What is the default value for class when sharing is not specified?

By default, every class runs in System mode or Admin mode if we do not specify any sharing keyword.

75.  What is the purpose of  extends keyword in salesforce?

A class that extends another class inherits all the methods and properties of the extended class. A class can only extend one other class, but it can implement more than one interface.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_extending.htm

76. What is an Interface?

An interface is like a class in which none of the methods have been implemented—the method signatures are there, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_interfaces.htm

77.  What is the purpose of final keyword?

Final variables can only be assigned a value once, either when you declare a variable or inside a constructor. You must assign a value to it in one of these two places.

78. What is the purpose of Dynamic Apex?

Dynamic Apex enables developers to create more flexible applications by providing them with the ability to:

Access sObject and field describe information

Access Salesforce app information

Dynamic SOQL and SOSL queries provide the ability to execute SOQL or SOSL as a string at runtime, while dynamic DML provides the ability to create a record dynamically and then insert it into the database using DML

79. How to access Recordtypeid dynamically without using soql query?

Id recordTypeId = Schema.SObjectType.Lead.getRecordTypeInfosByName().get(‘Record Type Name‘).getRecordTypeId();

In the Record type Name mention your desired record type Name that is available in your org.

80. How to get the sobject describe result through dynamic apex?

To access the describe result for an sObject, use one of the following methods:

  • Call the getDescribe method on an sObject token.
  • Use the Schema sObjectType static variable with the name of the sObject. For example, Schema.sObjectType.Lead.
  • Schema.DescribeSObjectResult is the data type for an sObject describe result.
    The following example uses the getDescribe method on an sObject token:

Schema.DescribeSObjectResult dsr = Account.sObjectType.getDescribe();
The following example uses the Schema sObjectType static member variable:
Schema.DescribeSObjectResult dsr = Schema.SObjectType.Account;

In this post, We will try to understand how to use a ternary operator in salesforce to reduce code. Ternary Operator acts as a short-hand for if-then-else statements.

x ?  y  : z

If x a boolean is true then the result will be y and If x a boolean is false then the result will be z.

Integer result= Condition? Valueone : Valuetwo;

Example(Ternary):

Integer currentmarketPrice = 25000;

Integer priormarketPrice = 15000;

Integer OppAmount = priormarketPrice > 15000 ? currentmarketPrice : priormarketPrice ;

If we do not use a ternary operator then we would have ended up implementing If then else logic with multiple lines of code.

Example(Without Ternary operator/If-else logic):

Integer OppAmount;

Integer currentmarketPrice = 25000;

Integer priormarketPrice = 15000;

If(priormarketPrice > 15000 )

{

OppAmount = currentmarketPrice;

} else {

OppAmount = priormarketPrice;

}

61. What are different types of collections in Apex?

Lists–A list is an ordered collection of elements that are distinguished by their indices. List elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.

Sets–A set is an unordered collection of elements that do not contain any duplicates. Set elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.

Maps–A map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.

62. What are different primitive datatypes used in Apex?

String, Integer, Boolean, Decimal, Date, Datetime

63. Is Apex Case sensitive?

Unlike Javascript, Lightning Webcomponents/Lightning Components, Apex is case Insensitive.

64. How are constants defined in Apex?

Constants can be defined using the final keyword.

Ex: static final Integer PRIVATE_INT_CONST = 200;

65. What does SOQL stand for and explain with an Example?

SOQL stands for Salesforce Object Query Language. This is used to query a list of records from the database.SOQL statements evaluate to a list of sObjects, a single sObject, or an Integer for count method queries.

List<Account> accnt = [SELECT Id, Name FROM Account WHERE Name = ‘salesforce’];

66. What are the Governor Limits on SOQL Queries?

Maximum number of SOQL queries issued in Synchronous(Trigger or Realtime) call is 100

Maximum number of SOQL queries issued in Asynchronous(Batch Apex, Queuable, Future) call is 200

67. How many records can be retrieved through a SOQL query?

Total number of records retrieved by SOQL queries is 50000

68.  What does SOSL stand for and explain with an Example?

SOSL stands for Salesforce object Search Language. SOSL always returns List of List of Sobject records.

SOSL statements evaluate to a list of lists of sObjects, where each list contains the search results for a particular sObject type. The result lists are always returned in the same order as they were specified in the SOSL query. If a SOSL query does not return any records for a specified sObject type, the search results include an empty list for that sObject.

List<List<SObject>> searchList = [FIND ‘map*’ IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead];

69.What is the consideration for selective SOQL Query Criteria?

  • A query is selective when one of the query filters is on an indexed field and the query filter reduces the resulting number of rows below a system-defined threshold. The performance of the SOQL query improves when two or more filters used in the WHERE clause meet the mentioned conditions.
  • The selectivity threshold is 10% of the first million records and less than 5% of the records after the first million records, up to a maximum of 333,333 records. In some circumstances, for example with a query filter that is an indexed standard field, the threshold can be higher. Also, the selectivity threshold is subject to change.

70. Define Aggregate functions in Salesforce?

Aggregate functions in SOQL, such as SUM() and MAX(), allow us to roll up and summarize data in a query. Aggregate functions become a more powerful tool to generate reports when you use them with a GROUP BY clause. For example, you could find the average Amount for all your opportunities by campaign.

AggregateResult[] groupedResults= [SELECT CampaignId, AVG(Amount) FROM Opportunity  GROUP BY CampaignId];

for (AggregateResult ar : groupedResults)  {

    System.debug(‘Campaign ID’ + ar.get(‘CampaignId’));

    System.debug(‘Average amount’ + ar.get(‘expr0’));

}

In this post, We will try to understand the key difference between With Sharing and without Sharing in Salesforce.

With Sharing Keyword: Apex by default runs in System mode or Admin mode. In Admin mode the class will have all the access to the field and object irrespective of running user’s permission. Any class that has With Sharing will enforce the Sharing rules for the current user. This has to be explicitly specified while writing the class as by default the class will have without sharing.

For Example: If a user with a Standard profile has access to Name or Address field on Account object then he/she will be able to only insert/update only Name and Address field. He/she will not be able to insert/update other fields as they do not have access to other fields as per profile access.

public with sharing class AccountsharingClass {

}

Without Sharing Keyword: Apex by default runs in without Sharing mode(ie admin mode/System mode).In Admin mode the class will have all the access to the field and object irrespective of running user’s permission. We could also explicitly specify without sharing keyword to ensure sharing rules are not imposed for the current user.

public without sharing class AccountsharingClass {

}

Note: If a method is defined in a class declared with with sharing is called

by a class declared with without sharing, the method executes with sharing 

rules are enforced. Ex: Lets assume we have two classes,Class A is created with

 “with sharing” and Class B iscreated with “without sharing”. If We call class A

from Class B then with sharing rules will be applied.

In this post, We will try to understand how to initiate Batchjob from Other Batch Job. Every Batch job consists of three methods such as Start, Execute, and Finish methods.

In the start method, we will query for the list of records from the desired object. Generally, We use Querylocator as it could hold up to 50 million records.

Execute method – All the business logic is processed inside the Execute method by using the list of records from the Start method

Finish method – This is the last method inside batch apex which will be executed after the Execute method. We could send an Email or Call a Batch job or do both inside this method.

Ex: We have two Batchjobs such as AccountBatch and ContactBatch.We could call ContactBatch from the finish method of AccountBatch

global class AccountBatch implements Database.Batchable<sObject>

{

    global Database.QueryLocator start(Database.BatchableContext BC)

    {

        String query = ‘SELECT Id,Name FROM Account’;

               return Database.getQueryLocator(query);

    }

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

    {

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

     for(Account acc : scope)

        {

            acc.Name = “Account Processed”;

            accList.add(acc);

        }

        update accList;

    }

    global void finish(Database.BatchableContext BC)

{

// Call Contactbatch job from AccountBatch

    ContactBatchJob contactJob = new ContactBatchJob();

   database.executebatch(contactJob);

    }

}

In this post, We will try to understand how to schedule a batch job in Salesforce to run every 30 mins. Salesforce User interface gives us the ability to only Schedule Apex classes on an hourly basis. If we want to schedule our batch class to run every 30 mins or to run at 12:30/1:30/2:30/3:30  this is not possible from user interface.

We could achieve the desired functionality from developer console. Run the below command to schedule the job to run for every 30 mins

Command for 30 mins:

system.schedule(‘AccSched30min’, ‘0 30 * * * ?’, new AccountSchedule());

Command for 15 mins:

system.schedule(‘AccSched15min’, ‘0 15 * * * ?’, new AccountSchedule());

Command for 45 mins:

system.schedule(‘AccSched45min’, ‘0 45 * * * ?’, new AccountSchedule());

Command for 10 mins:

system.schedule(‘AccSched10min’, ‘0 10 * * * ?’, new AccountSchedule());

From Schedule Jobs check for the jobs that were scheduled.

51. If i have two triggers(Accttrigger and accounttrigger) on the Same object(Account) with
Same event(after insert), can i know which trigger will fire first?

No we cannot determine which trigger can be fired first. In order to control the execution, write a trigger per object and call an Apex class where we can control the Execution.

52. Can we Call a Future method from trigger?

Yes we can call a future method from trigger. This feature is helpful to call a Webservice /Callout process.

53. Can we invoke a Schedule Job from Trigger?

We can invoke a Schedule job from Trigger.

54. Can we invoke a Batch Apex class from Trigger?

We can invoke a Batch Class from Trigger

trigger acctTrigger on Account(before insert,before update){

AccountBatch accBatch = new AccountBatch();

Database.executeBatch(accBatch);

}

55. Can we Skip triggers for desired users or profiles in Salesforce?

We can skip triggers using Hierarchical Custom settings in salesforce for Desired profile.

56. When should we use before trigger vs after trigger?

As a groundrule, always use before triggers when you donot want to act on the Id of the record.Since before triggers doesnot require any DML it also helps in reducing DML and increasing performance compared to After Triggers. Use After triggers if we want to perform operations after the record is inserted(example Id is generated) and we want to perform operations on the child entities based on the record inserted. Ex: If we want to insert a contact record after an account is inserted then we need to write an After insert trigger on Account object and based on the account id we will insert the contact and associate Account id to it.

57.  Can we send Emails using Triggers?

Yes, We can send Emails using Triggers.The maximum number of Emails that could be sent is 5000 per org depending on Edition(Enterprise/Unlimited).

58. What are best practices in triggers?

a.Always write one trigger per object with all events.

b.For controlled execution write a trigger and call a Class and define methods in desired order.

c.Always write trigger to process a minimum of 200 records in single transaction

d. Avoid SOQL queries inside for loop as it will result in Governor Limits.

e. Avoid DML statements inside for Loop as it will result in Governor Limits.

59. Will the Triggers be fired if there is an workflow/process builder that performs an action?

Before update and After update triggers will be refired when a field update occurs from processbuilder/workflow.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_order_of_execution.htm

41. What is Recursion and when does this issue occur?

Recursion is the process of executing the same piece of code infinite times. Eventually, this will result in hitting Governor limits in Salesforce. This issue occurs when we have an after Update Trigger event along the Process builder/Workflow field update acting on the Same field.

Example: If we have an After update trigger on Opportunity that is trying to Update a stage field and we also have a process builder/workflow on Stage field this will result in Recursion as the trigger update will fire the Process builder/workflow and process builder/workflow is again going to invoke trigger. This will keep on executing infinite times and eventually, the process results in hitting governor Limit.

hitting governor Limit.

42. How to avoid Recursion in Salesforce?

We can avoid recursion in Salesforce by using a static helper method. Read below for complete details of Recursion

43.  What is DML in salesforce?

DML(Data Manipulation Language) in Salesforce provides the ability to manage records using insert, Update, Delete and Restore statements

44. What are different DML Statements in Salesforce?

insert,update,upsert,delete,undelete,merge

45. What is the difference between update and upsert?

update statement helps in updating the record based on recordId. Upsert DML statement creates the record if there is no existing record and if a record exists then it will update the record.

46. Will any records be deleted during merge process?

The merge statement merges up to three records of the same sObject type into one of the records, deleting the others, and re-parenting any related records.

47. What are different Database methods in Salesforce?

  • Database.insert()
  • Database.update()
  • Database.upsert()
  • Database.delete()
  • Database.undelete()
  • Database.merge()

48. What is difference between DML Statements and Database methods?

Unlike DML statements, Database methods have an optional allOrNone parameter that allows you to specify whether the operation should partially succeed. When this parameter is set to false, if errors occur on a partial set of records, the successful records will be committed and errors will be returned for the failed records.

Note: No exceptions are thrown with the partial success option.

49. Can i insert partial records in a Transaction?

Yes we can insert partial records in a transaction using Database method with allorNone parameter set to false.

Ex:  Database.SaveResult[] results = Database.insert(recordList, false);

50. Please provide a sample code that process partial records in salesforce?

Execute the below piece of code in Execute Anonymous window of Developer Console

// Create a list of contacts

List<Contact> conList = new List<Contact> {

        new Contact(FirstName=’Joe’,LastName=’Smith’,Department=’Finance’),

        new Contact(FirstName=’Kathy’,LastName=’Smith’,Department=’Technology’),

        new Contact(FirstName=’Caroline’,LastName=’Roth’,Department=’Finance’),

        new Contact()};

// Bulk insert all contacts with one DML call

Database.SaveResult[] srList = Database.insert(conList, false);

// Iterate through each returned result

for (Database.SaveResult sr : srList) {

    if (sr.isSuccess()) {

        // Operation was successful, so get the ID of the record that was processed

        System.debug(‘Successfully inserted contact. Contact ID: ‘ + sr.getId());

    } else {

        // Operation failed, so get all errors

        for(Database.Error err : sr.getErrors()) {

            System.debug(‘The following error has occurred.’);

            System.debug(err.getStatusCode() + ‘: ‘ + err.getMessage());

            System.debug(‘Contact fields that affected this error: ‘ + err.getFields());

}

    }

}

31.  What is the difference between trigger.old and trigger.new?

Trigger.old contains lists of old records(old field values) and Trigger.new contains list of new records(new field values). Ex: If we have written a trigger on Account, trigger.new contains list of new Account records and trigger.old contains list of old Account records.

32. What is the difference between trigger.oldmap and trigger.newmap?

Trigger.oldmap contains map of oldSobjectrecords with key as Id’s and Trigger.newmap contains map of  Id’s of sobjectrecords.

Note: Trigger.oldmap is only available in update and delete Triggers. Trigger.newmap is only available in before update, after insert, after update, and after undelete triggers.

33. What are the different types of events in the trigger?

A trigger can be invoked with 7 events

Before insert, Before Update, After insert, After update, Before delete,After delete,After undelete

34. Explain best practices in Trigger?

We should write one trigger per object by defining all events. We should call a class from trigger to handle processing logic so that we can control the execution. Optionally we could also write event-based triggers per object but maintaining this would be difficult. Since we have 7 events we can have 7 triggers per object.

35. What is the default size of records that a trigger can process?

By default, the processing size of trigger is 200. But there are exceptions to this rule. For example: If we are loading records through data loader and you have changed the record size to 500 then the trigger will fire for 500 records at a time.

36. What are the operations that don’t invoke triggers?

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_ignoring_operations.htm

37. What is bulkification?

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_bulk_idioms.htm

38. Can I perform DML Operations on trigger.new and trigger.old context variable?

No, you cannot perform DML Operations on trigger.new and trigger.old context Variable.

39. Explain Sample trigger code with different trigger events?

trigger myAccountTrigger on Account(before delete, before insert, before update, 

                                    after delete, after insert, after update) {

if (Trigger.isBefore) {

    if (Trigger.isDelete) {

        // In a before delete trigger, the trigger accesses the records that will be

        // deleted with the Trigger.old list.

        for (Account a : Trigger.old) {

            if (a.name != ‘okToDelete’) {

                a.addError(‘You can\’t delete this record!’);

            } 

        }

    } else {

    // In before insert or before update triggers, the trigger accesses the new records

    // with the Trigger.new list.

        for (Account a : Trigger.new) {

            if (a.name == ‘bad’) {

                a.name.addError(‘Bad name’);

            }

    }

    if (Trigger.isInsert) {

        for (Account a : Trigger.new) {

            System.assertEquals(‘xxx’, a.accountNumber); 

            System.assertEquals(‘industry’, a.industry); 

            System.assertEquals(100, a.numberofemployees);

            System.assertEquals(100.0, a.annualrevenue);

            a.accountNumber = ‘yyy’;

        }

// If the trigger is not a before trigger, it must be an after trigger.

} else {

    if (Trigger.isInsert) {

        List<Contact> contacts = new List<Contact>();

        for (Account a : Trigger.new) {        

            if(a.Name == ‘makeContact’) {

                contacts.add(new Contact (LastName = a.Name,

                                          AccountId = a.Id));

            }

        } 

      insert contacts;

    }

  }

}}}