Concepts or coding lessons of Salesforce that you can implement easily

Salesforce Interview Questions - Part 6


121. What are the Trigger Best Practices?
Answer :
Best Practice #1: One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts. Many times, the order of execution doesn’t matter but when it does matter, it’s nearly impossible to maintain proper flow control. A single Trigger can handle all possible combinations of Trigger contexts which are:

  • before insert
  • after insert
  • before update
  • after update
  • before delete
  • after delete
  • after undelete

So as a best practice, create one Trigger per object and let it handle all of the contexts that you need. Here is an example of a Trigger that implements all possible contexts:

trigger OpportunityTrigger on Opportunity (
  before insert, before update, before delete, 
  after insert, after update, after delete, after undelete) {

  // trigger body

}


Best Practice #2: Bulkify your Helper Methods
Make sure any code that runs a query or DML operation does it in a bulk manner and doesn't execute within an iteration or a for loop. Executing queries or DML operations within an iteration adds risk that the governor limits will be exceeded. This is also true for any helper or utility methods an Apex request executes.
Governor limits are calculated at runtime. After the request is initiated (Trigger, Visualforce page, etc.), any Apex code executed in that transaction applies and shares the governor limits. So if a trigger uses some Apex methods written in a helper class, it's important that those shared Apex methods are properly designed to handle bulk records. These methods should be written to be invoked with a set of records, especially if the method has a SOQL query or DML operation.
For example, if the Apex method performs a SOQL query, that method should receive a collection (Array, List, Set, etc.) of records so when it performs the query, it can perform the query for all records in the Apex transaction. Otherwise, if the Apex method is called individually for each record being processed, the Apex transaction will inefficiently run queries and possibly exceed the allowed number of queries allowed in that transaction. The same is true for DML statements in Apex methods.
So please make sure any utility or helper methods are efficiently written to handle collections of records. This will avoid unnecessarily executing inefficient queries and DML operations.
Best Practice #3: Logic-less Triggers
Another widely-recognized best practice is to make your Triggers logic-less. That means, the role of the Trigger is just to delegate the logic responsibilities to some other handler class. There are many reasons to do this. For one, testing a Trigger is difficult if all of the application logic is in the trigger itself. If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org. 
Good old OO principles tell us that this is a bad practice. And to top it all off, cramming all of your logic into a Trigger is going to make for a mess one day. To remedy this scenario, just create a handler class and let your Trigger delegate to it. Here is an example:
trigger OpportunityTrigger on Opportunity (after insert) {
OpportunityTriggerHandler.handleAfterInsert(Trigger.new);
}
And the handler class:

public class OpportunityTriggerHandler {

  public static void handleAfterInsert(List opps) {
    // handler logic
  }
}

Best Practice #4: Avoid SOQL Queries or DML statements inside FOR Loops
A common mistake is that queries or DML statements are placed inside a for loop. There is a governor limit that enforces a maximum number of SOQL queries. There is another that enforces a maximum number of DML statements (insert, update, delete, undelete). When these operations are placed inside a for loop, database operations are invoked once per iteration of the loop making it very easy to reach these governor limits.
Instead, move any database operations outside of for loops. If you need to query, query once, retrieve all the necessary data in a single query, then iterate over the results. If you need to modify the data, batch up data into a list and invoke your DML once on that list of data.

Best Practice #5: Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits.

Best Practice #6: Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore.

For example, if the results are too large, the syntax below causes a runtime exception:
//A runtime exception is thrown if this query returns enough records to exceed your heap limit.
Account[] accts = [SELECT id FROM account];

Instead, use a SOQL query for loop as in one of the following examples:

// Use this format for efficiency if you are executing DML statements 
// within the for loop.  Be careful not to exceed the 150 DML statement limit.

Account[] accts = new Account[];

for (List<Account> acct&nbsp;: [SELECT id, name FROM account
                            WHERE name LIKE 'Acme']) {
    // Your logic here
    accts.add(acct);
}

update accts;

Let the Force.com platform chunk your large query results into batches of 200 records by using this syntax where the SOQL query is in the for loop definition, and then handle the individual datasets in the for loop logic.

Best Practice #7: Use of the Limits Apex Methods to Avoid Hitting Governor Limits
Apex has a System class called Limits that lets you output debug messages for each governor limit. There are two versions of every method: the first returns the amount of the resource that has been used in the current context, while the second version contains the word limit and returns the total amount of the resource that is available for that context.


122. What are Apex Unit Tests?
Answer: 
To facilitate the development of robust, error-free code, Apex supports the creation and execution of unit tests. Unit tests are class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit no data to the database, send no emails, and are flagged with the testMethod keyword or the isTest annotation in the method definition. Also, test methods must be defined in test classes, that is, classes annotated with isTest.
For example:
@isTest
private class myClass {
     static testMethod void myTest() {
        // code_block
    }
}

This is the same test class as in the previous example but it defines the test method with the isTest annotation instead.
@isTest
private class myClass {
    @isTest static void myTest() {
        // code_block
    }
}

123. What are the Unit Test Considerations ?
Answer :
Here are some things to note about unit tests.


  • Starting with Salesforce API 28.0, test methods can no longer reside in non-test classes and must be part of classes annotated with isTest. See the TestVisible annotation to learn how you can access private class members from a test class.
  • Test methods can’t be used to test Web service callouts. Instead, use mock callouts. See Test Web Service Callouts and Testing HTTP Callouts.
  • You can’t send email messages from a test method.
  • Since test methods don’t commit data created in the test, you don’t have to delete test data upon completion.
  • If a test class contains a static member variable, and the variable’s value is changed in a testSetup or test method, the new value isn’t preserved. Other test methods in this class get the original value of the static member variable. This behavior also applies when the static member variable is defined in another class and accessed in test methods.
  • For some sObjects that have fields with unique constraints, inserting duplicate sObject records results in an error. For example, inserting CollaborationGroup sObjects with the same names results in an error because CollaborationGroup records must have unique names.
  • Tracked changes for a record (FeedTrackedChange records) in Chatter feeds aren't available when test methods modify the associated record. FeedTrackedChange records require the change to the parent record they're associated with to be committed to the database before they're created. Since test methods don't commit data, they don't result in the creation of FeedTrackedChange records. Similarly, field history tracking records (such as AccountHistory) can't be created in test methods because they require other sObject records to be committed first (for example, Account).

124. How do you unit test a trigger when you don’t know the required fields?
Answer :
Customers can have validation on custom fields via validation rules and triggers, so handling that in your unit tests without customer intervention is next to impossible. The first step to reducing issues is to have your test data populate all standard fields and ensure the data uses the most common formatting for your customer base (US style phone numbers and addresses for the US for example).

Beyond that you can use the new Reflection features added to Salesforce in Summer ’12 to allow customers to create unit test data classes that can be used by your managed package. Basically you define a test data generation interface and the customer creates an Apex class to generate data for you. Here’s an example of using Reflection in a similar manner on the DeveloperForce blog:http://blogs.developerforce.com/developer-relations/2012/05/dynamic-apex-class-instantiation-in-summer-12.html

Using the method for unit tests run on install might be problematic as you’d have to have the customer create the class before they install your package and your package could only look for the class by name (or iterate through all default namespace classes and check for the correct interface). However, it’s no longer necessary for unit tests to run during installation for managed packages and by default they do not.

The Reflection method requires some coding knowledge on the customer side, but you could add a tool in your application to generate the custom unit test data class for the customer.

FYI, it’s no longer necessary for managed package unit tests to succeed in customer orgs. They’re not required on install, they will no longer prevent deployment to production and they don’t count as part of the customers unit test coverage percentage for purposes of deployment. The only exception to that is if the customer uses ANT and sets the runAllTests parameter to true.

125. How do you write a unit test for a trigger whose only function is to make a callout?
Answer :
Both future methods and callouts can be unit tested.

To test future methods simply make your call to any future method between Test.startTest();and Test.stopTest(); statements and the future method will return when Test.stopTest(); is called. See the documentation for the Test class here: System.Test

Testing callouts is a bit trickier though. Basically in your callout code you check to see if you’re executing within a unit test context by checking Test.isRunningTest() and instead of getting your callout response from an HttpResponse.send() request, you return a pre-built test string instead. There’s one example of this method here: http://www.iterativelogic.com/unit-test-callouts-in-apex-code-part-2/


There’s also an older example of callout unit testing that uses a static variable you set in your unit test. Just replace that static variable with a call to Test.isRunningTest() and their example works fairly well as well. That example can be found here:http://sfdc.arrowpointe.com/2009/05/01/testing-http-callouts/

126. Can I find out if the current user has access to a record without querying?
Answer :
To find out if a particular user has Edit access to a record, use the UserRecordAccess object. This object is available in API version 24.0 and later. You can use SOQL to query this object to find out if the user has edit access to the record in question.

SELECT RecordId, HasEditAccess FROM UserRecordAccess WHERE UserId = [single ID] AND RecordId = [single ID]

If you want to check a batch of records you can use

SELECT RecordId FROM UserRecordAccess WHERE UserId=:UserInfo.getUserId() AND HasReadAccess = true ANDRecordId IN :allRecordIds LIMIT 200

But make sure that allRecordIds is a LIST of IDs. It doesn’t work if allRecordIds is a SET of IDs. I guess that’s a bug.


Also, only a maximum amount of 200 recordIds can be checked in one query.


122. What are Apex Unit Tests?
Answer: 
To facilitate the development of robust, error-free code, Apex supports the creation and execution of unit tests. Unit tests are class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit no data to the database, send no emails, and are flagged with the testMethod keyword or the isTest annotation in the method definition. Also, test methods must be defined in test classes, that is, classes annotated with isTest.
For example:
@isTest
private class myClass {
     static testMethod void myTest() {
        // code_block
    }
}

This is the same test class as in the previous example but it defines the test method with the isTest annotation instead.
@isTest
private class myClass {
    @isTest static void myTest() {
        // code_block
    }
}

123. What are the Unit Test Considerations ?
Answer :
Here are some things to note about unit tests.


  • Starting with Salesforce API 28.0, test methods can no longer reside in non-test classes and must be part of classes annotated with isTest. See the TestVisible annotation to learn how you can access private class members from a test class.
  • Test methods can’t be used to test Web service callouts. Instead, use mock callouts. See Test Web Service Callouts and Testing HTTP Callouts.
  • You can’t send email messages from a test method.
  • Since test methods don’t commit data created in the test, you don’t have to delete test data upon completion.
  • If a test class contains a static member variable, and the variable’s value is changed in a testSetup or test method, the new value isn’t preserved. Other test methods in this class get the original value of the static member variable. This behavior also applies when the static member variable is defined in another class and accessed in test methods.
  • For some sObjects that have fields with unique constraints, inserting duplicate sObject records results in an error. For example, inserting CollaborationGroup sObjects with the same names results in an error because CollaborationGroup records must have unique names.
  • Tracked changes for a record (FeedTrackedChange records) in Chatter feeds aren't available when test methods modify the associated record. FeedTrackedChange records require the change to the parent record they're associated with to be committed to the database before they're created. Since test methods don't commit data, they don't result in the creation of FeedTrackedChange records. Similarly, field history tracking records (such as AccountHistory) can't be created in test methods because they require other sObject records to be committed first (for example, Account).

124. How do you unit test a trigger when you don’t know the required fields?
Answer :
Customers can have validation on custom fields via validation rules and triggers, so handling that in your unit tests without customer intervention is next to impossible. The first step to reducing issues is to have your test data populate all standard fields and ensure the data uses the most common formatting for your customer base (US style phone numbers and addresses for the US for example).

Beyond that you can use the new Reflection features added to Salesforce in Summer ’12 to allow customers to create unit test data classes that can be used by your managed package. Basically you define a test data generation interface and the customer creates an Apex class to generate data for you. Here’s an example of using Reflection in a similar manner on the DeveloperForce blog:http://blogs.developerforce.com/developer-relations/2012/05/dynamic-apex-class-instantiation-in-summer-12.html

Using the method for unit tests run on install might be problematic as you’d have to have the customer create the class before they install your package and your package could only look for the class by name (or iterate through all default namespace classes and check for the correct interface). However, it’s no longer necessary for unit tests to run during installation for managed packages and by default they do not.

The Reflection method requires some coding knowledge on the customer side, but you could add a tool in your application to generate the custom unit test data class for the customer.

FYI, it’s no longer necessary for managed package unit tests to succeed in customer orgs. They’re not required on install, they will no longer prevent deployment to production and they don’t count as part of the customers unit test coverage percentage for purposes of deployment. The only exception to that is if the customer uses ANT and sets the runAllTests parameter to true.

125. How do you write a unit test for a trigger whose only function is to make a callout?
Answer :
Both future methods and callouts can be unit tested.

To test future methods simply make your call to any future method between Test.startTest();and Test.stopTest(); statements and the future method will return when Test.stopTest(); is called. See the documentation for the Test class here: System.Test

Testing callouts is a bit trickier though. Basically in your callout code you check to see if you’re executing within a unit test context by checking Test.isRunningTest() and instead of getting your callout response from an HttpResponse.send() request, you return a pre-built test string instead. There’s one example of this method here: http://www.iterativelogic.com/unit-test-callouts-in-apex-code-part-2/


There’s also an older example of callout unit testing that uses a static variable you set in your unit test. Just replace that static variable with a call to Test.isRunningTest() and their example works fairly well as well. That example can be found here:http://sfdc.arrowpointe.com/2009/05/01/testing-http-callouts/

126. Can I find out if the current user has access to a record without querying?
Answer :
To find out if a particular user has Edit access to a record, use the UserRecordAccess object. This object is available in API version 24.0 and later. You can use SOQL to query this object to find out if the user has edit access to the record in question.

SELECT RecordId, HasEditAccess FROM UserRecordAccess WHERE UserId = [single ID] AND RecordId = [single ID]

If you want to check a batch of records you can use

SELECT RecordId FROM UserRecordAccess WHERE UserId=:UserInfo.getUserId() AND HasReadAccess = true ANDRecordId IN :allRecordIds LIMIT 200

But make sure that allRecordIds is a LIST of IDs. It doesn’t work if allRecordIds is a SET of IDs. I guess that’s a bug.


Also, only a maximum amount of 200 recordIds can be checked in one query.


More Salesforce Interview Questions and Answers:


Salesforce Interview Questions - Part 5

101. What is the difference between public cloud & private cloud in salesforce? Is salesforce.com a public cloud or private cloud?
Answer :
Public Cloud: Could services are provided "as a service" over the Internet with little or no control over the underlying technology infrastructure. More than one tenant can use the same resources.
Private Cloud: This also offers activities and functions "as a service" but is deployed over a company intranet or hosted data center. This is private product for a company or organization offering advance security.
Salesforce.com: Is a public cloud as it is hosted on salesforce.com data centers and data of more than one tenant resides on same servers.

102. What is the difference between apex:pageMessages, apex:pageMessage, apex:Message and apex:Messages?
Answer :
apex:PageMessages:

This component displays all messages that were generated for all components on the current page, presented using the salesforce styling. This will display both salesforce generated messages as well as custom messages added to the ApexPages class 

apex:PageMessage:

Apex:PageMessage is a component that adds single message on the page. This is used to display custom message using the salesforce formatting

apex:Message:

apex:Message is used to display an error on only a specific field. It is used to allow developers to place field specific errors in specific location.

apex:Messages:

apex:Messages is similar to apex:Message but it displays all errors


103. What are the aggregate functions supported by salesforce SOQL?
Answer :
Following aggregate functions are supported by salesforce SOQL
1. SUM()
2. MIN()
3. MAX()
4. COUNT()
5. AVG()
6. COUNT_DISTINCT()

104. Write a sample aggregate query or explain how to write a aggregate queries?
Answer :
The return types of Aggregate functions are always an array of AggregateResult.

Sample Code

AggregateResult[] ar = [select AVG(Amount) aver from Opportunity];
Object avgAmt = ar[0].get('aver’);

105. Write a code to find the average Amount for all your opportunities by campaign?
Answer :
AggregateResult[] arList = [select CampaignId, AVG(amount) from Opportunity group by CampaignId];
for(AggregateResult ar : arList){
    System.debug('CampaignId ' + ar.get('CampaignId'));
    System.debug('Average Amount' + ar.get('expr0'));
}



106. What are groups in SFDC and what is their use in salesforce?
Answer :
Groups are set of users. They can contain individual users, other groups, the users in a particular role or territory, or the users in a particular role or territory plus all of the users below that role or territory in the hierarchy.
There are two types of groups:
•  Public groups: Only administrators can create public groups. They can be used by everyone in the organization.
•  Personal groups: Each user can create groups for their personal use.
You can use groups in the following ways:
•  To set up default sharing access via a sharing rule
•  To share your records with other users
•  To specify that you want to synchronize contacts owned by others users
•  To add multiple users to a Salesforce CRM Content library
•  To assign users to specific actions in Salesforce Knowledge

107. Write a syntax and structure of scheduler class?
Answer :
Sample class

global class ScheduleDemo implements Schedulable{
    global void execute(SchedulableContext sc){
        BatchClass b = new BatchClass();
        database.executeBatch(b);
}
}

108 .How to schedule export or take the backup of salesforce?
Answer :
Step by Step Instruction:

  • Click Setup >Data Management > Data Export > Schedule Export.
  • Select the desired encoding for your export file. Leaving the default is fine.
  • Check the Include in export checkbox if you want to include attachments in the export (optional)
  • Leave the default Replace carriage returns with spaces if you want your export files to have spaces instead of carriage returns.
  • Select Weekly as the frequency for the exports.
  • Choose start and end dates. Set the end date to sometime in the distant future such as 20 years from the begin date.
  • Set the time of day for your scheduled export. The export is put in a job queue and the exact time of the export will depend on the amount of activity in the queue.
  • You can select the types of data to include in your export. It is best to include all data in your export file. This will make sure all your organizations data is exported.
  • Click Save.

Points to Remember:

  • Formula and roll-up summary fields are never included in exports.
  • Articles are not included from exports.
  • The export notification email is sent to the email address on file for the user who created the scheduled export. There is no way to indicate another email address. If as an Administrator you want the email to go to another person, have them grant you login access, login as them and schedule the data export.
  • Important:
  • Scheduled backup exports of your data are limited to weekly exports.
  • You have 48 hours from the time you are notified the backup is available to download the backup file.
  • The email notification for backups goes to the email address in Salesforce of the person logged in who schedules the backup.


109. How to import attachments using Data Loader in salesforce?
Answer :
Please follow the instructions below.

1. Create an AttachmentList.csv file with the following column headers:
• ParentId - ID of the record to which the attachment should be associated 
• Name - Name of the attachment 
• ContentType - Format of the extension (e.g. .xls, .pdf, etc) 
• OwnerID - ID for the owner of the attachment
• Body - File path to the Attachment on your local machine (C:\Attachments\YourAttachmentFileName.pdf)
2. Log in to the Data Loader. 
3. Select the "Insert" command. 
4. In the 'Select Sforce Object' step, select the 'Attachments’ object. This object is not displayed by default hence check the 'Show all Sforce Objects' checkbox. 
5. Choose the AttachmentList.csv file. 
6. In the mapping step, map the following fields:
• Parent ID 
• Name 
• Owner ID 
• Body - Make sure to map the Body column which you created previously with the file extension. This is how you designate the file and location of the attachments to be inserted. 
7. Click "OK" to start the upload.

110. What is the difference between custom controller and extension in salesforce?
Answer :
Custom Controller: A custom controller is an Apex class that implements all of the logic for a page without leveraging a standard controller. Use custom controllers when you want your Visualforce page to run entirely in system mode, which does not enforce the permissions and field-level security of the current user.
Controller extension: A controller extension is an Apex class that extends the functionality of a standard or custom controller. Use controller extensions when:
• You want to leverage the built-in functionality of a standard controller but override one or more actions, such as edit, view, save, or delete.
• You want to add new actions.
• You want to build a Visualforce page that respects user permissions. Although a controller extension class executes in system mode, if a controller extension extends a standard controller, the logic from the standard controller does not execute in system mode. Instead, it executes in user mode, in which permissions, field-level security, and sharing rules of the current user apply.
A controller extension is any Apex class containing a constructor that takes a single argument of type ApexPages.StandardController or CustomControllerName, whereCustomControllerName is the name of a custom controller you want to extend.
Note: Although custom controllers and controller extension classes execute in system mode and thereby ignore user permissions and field-level security, you can choose whether they respect a user's organization-wide defaults, role hierarchy, and sharing rules by using the with sharing keywords in the class definition.


111. Difference between with sharing and without sharing in salesforce ?
Answer :
By default, all Apex executes under the System user, ignoring all CRUD, field-level, and row-level security (that is always executes using the full permissions of the current user).
without sharing:
Enforcing the User’s Permissions, Sharing rules and field-level security should apply to the current user.
For example:
public with sharing class sharingClass {
// your Code here
}
without sharing:
Not enforced the User’s Permissions, Sharing rules and field-level security.
For example:
public without sharing class noSharing {
// your Code here
}
Enforcing the current user’s sharing rules can impact: (with sharing)
SOQL and SOSL queries – A query may return fewer rows than it would operating in system context.
DML operations – An operation may fail because the current user doesn’t have the correct permissions. For example, if the user specifies a foreign key value that exists in the organization, but which the current user does not have access to.

112. What are email services in salesforce and explain how we can use them in code?
Answer :
Email services are automated processes that use apex class to process the contents, headers and attachment of an inbound email.

Sample code

Use Case: create a contact record if the inbound email subject is Create Contact and body contains contact name

global CreateContactFromEmail implements Messaging.InboundEmailHandler{
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelop envelop){
    Messaging.InboundEmailResult res = new Messaging.InboundEmailResult();
    String strToCompare = 'Create Contact’;
    If(email.subject.equalsIgnoreCase(strToCompare)){
        Contact c = new Contact();
        c.LastName = email.plainTextBody();
        insert c;
        
        //save text attachments

for(Messaging.InboundEmail.TextAttachment att : email.textAttachments){
    Attachment a = new Attachment();
    a.Name = att.fileName;
    a.Body = att.Blob.valueOf(att.Body);
    a.ParentId = c.Id;
    insert attachment;
}
        
//save binary attachments

for (Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
            Attachment attachment = new Attachment();
            attachment.Name = bAttachment.fileName;
            attachment.Body = bAttachment.body;
            attachment.ParentId = c.Id;
            insert attachment;
}
}
res.Success = true;
return res;
}
}

113. What is Wrapper Class in Apex Salesforce ?
Answer :
Wrapper class is collections of different data type, subject etc.

In following example  we are  bind Account ,Opportunity standard object. We query and perform

business logic on the Collection of elements across unrelated objects with the custom data type.


Visual Force Page:

<apex:page controller="wrapperDemoCtrl">

<apex:pageBlock title="Account From wrapper  Class">

   <apex:pageBlockTable value="{!wraccount}" var="wra">

   <apex:column value="{!wra.acc.Name}"/>

   </apex:pageBlockTable>

</apex:pageBlock>

<apex:pageBlock title="Opportunity From wrapper  Class">

   <apex:pageBlockTable value="{!wraoppn}" var="wropp">

   <apex:column value="{!wropp.op.Name}"/>

   </apex:pageBlockTable>

</apex:pageBlock>


</apex:page>

Apex Controller :

public class wrapperDemoCtrl {

    public list<wrapperClass> wraplist{get;set;}
  
    public list<wrapperClass> getwraccount()
          {
            list<Account>acclist=[select Id,Name from Account limit 3];
            wraplist= new list<wrapperClass>();
            for(Account acn: acclist)
            {
            wraplist.add(new wrapperClass(acn));
            }
           return wraplist;
          }
    public list<wrapperClass> getwraoppn()
        {
         list<Opportunity>opplist=[select Id,Name from Opportunity limit 3];
         wraplist= new list<wrapperClass>();
         for(Opportunity opn:opplist )
         {
         wraplist.add(new wrapperClass(opn));
         }
         return wraplist;
        }
  
    public class wrapperClass{
  
        public Account acc {get;set;}
        public Opportunity op {get;set;}
      
        public wrapperClass(Account accn){
      
                 acc= accn;         
                     }
       public wrapperClass(Opportunity opn)
       {
         op=opn;
      
       }
    }
}

114. How can we hard delete a record using a Apex class/by code?
Answer :
ALL ROWS key word can be used to get all the records including records in the recycle bin.
Below is the sample code to delete contact records from recycle bin
List<Contact> dContactList=[Select ID From Contact Where IsDeleted = true limit 199 ALL ROWS];
Database.emptyRecycleBin( dContactList );

How do you do File Upload using visualforce?
Answer :
Below is the code sample of file upload in visualforce
<!-- Upload a file and put it in your personal documents folder-->
<!-- Page: -->
<apex:page standardController="Document" extensions="documentExt">
<apex:messages />
<apex:form id="theForm">
<apex:pageBlock>
<apex:pageBlockSection>
<apex:inputFile value="{!document.body}" filename="{!document.name}"/>
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
/*** Controller ***/
public class documentExt {
public documentExt(ApexPages.StandardController controller) {
        Document d = (Document) controller.getRecord();
        d.folderid = UserInfo.getUserId(); //this puts it in My Personal Documents
    }                
}

115. Explain Class Constructors with example?
Answer :
• A constructor is a special method used to create (or instantiate) an object out of a class definition.
• Constructors never have explicit return types.
• Constructors have the same name as the class.
• Classes have default, no-argument, public constructor if no explicit constructors is defined.
• If you create a constructor that takes arguments and still want a no-argument constructor, you must explicitly define one.
• Constructors can be overloaded, meaning you can have multiple constructors with different parameters, unique argument lists, or signatures.
• Constructors are called before all other methods in the class.
For Example:
public class TestObject2 {
private static final Integer DEFAULT_SIZE = 10;
Integer size;
//Constructor with no arguments
public TestObject2() {
this(DEFAULT_SIZE); // Using this(…) calls the one argument constructor
}
// Constructor with one argument
public TestObject2(Integer ObjectSize) {
size = ObjectSize;
}
}
New objects of this type can be instantiated with the following code:
TestObject2 myObject1 = new TestObject2(20);
TestObject2 myObject2 = new TestObject2();


116. What are the available Trigger Events?
Answer :
There are 6 trigger events available.
1. Insert
2. Update
3. Delete
4. Merge
5. Upsert
6. Undelete

117. What are the available Trigger contest variables?
Answer :
Below are the list of Trigger context variables
1. isBefore
2. IsAfter
3. isInsert
4. IsUpdate
5. isDelete
6. isUndelete
7. isExecuting
8. new
9. old
10. newMap
11. oldMap
12. size

118. Let’s say we have to update the same record in After Trigger context. Is there any way or workaround?
Answer :
If we create a new instance of a sObject in the Apex Trigger in memory using the Id of the newly created record as provided in the After Trigger context, we can perform an Update DML statement and not get a read only error. This is because in Apex, the SObject is seen as a new reference (even though the records have the same SFDC ID) and therefore is eligible for DML operations. The below snippet of code illustrated this working and not working.
List<Contact> originals = new List<Contact>();
if(mirrorResultMap.values().size() > 0)
{
    for(Contact origContact : contactRecs.values())
    {
        Contact mirrorContact = mirrorResultMap.get(origContact.Id);
        //origContact.Linked_Contact__c = mirrorContact.Id; //Link the Original Record i.e. Mirror Record WILL FAIL
        Contact origContactUpdate = new Contact(Id=origContact.Id, Linked_Contact__c = mirrorContact.Id); //This will WORK
        originals.add(origContactUpdate);
    }
    //update contactRecs.values(); //Update the Records -> THIS WILL FAIL AS ITS ORIGINAL RECORDS IN MEMORY
    update originals;
}

119. How to get the picklist value in Apex class?
Answer :
Using Dynamic apex, we can achieve this. On object of type pickilist, call getDescribe(). Then call the getPicklistValues() method. Iterate over result and create a list. Bind it to <apex:selectOptions>.
Code Example:
Let’s say we have a custom object called OfficeLocation__c. This object contains a picklist field Country__c.
The first thing we need to do, within our controller is use the getDescribe() method to obtain information on
the Country__c field:
Schema.DescribeFieldResult fieldResult = OfficeLocation__c.Country__c.getDEscribe();
We know that Country__c is a picklist, so we want to retrieve the picklist values:
List<Schema.PicklistEntry> ple = fieldResult.gerPicklistValues();
The only thing left for us to do is map the picklist values into an <apex:selectOptions> tag can use for display. Here is the entire method from our controller to do this:
public List<SelectOption> getCountries()
{
  List<SelectOption> options = new List<SelectOption>();
        
   Schema.DescribeFieldResult fieldResult =
 OfficeLocation__c.Country__c.getDescribe();
   List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        
   for( Schema.PicklistEntry f : ple)
   {
      options.add(new SelectOption(f.getLabel(), f.getValue()));
   }       
   return options;
}
With our controller logic all complete, we can call the getCountries() method from our Visualforce page,  and populate the <apex:selectList> tag:
<apex:selectList id="countries" value="{!Office_Location__c.Country__c}"
         size="1" required="true">
  <apex:selectOptions value="{!countries}"/>
</apex:selectList>

120. What are the Salesforce annotations ?
Answer :
Apex annotations modify the way a method or class is used.
Below is the list of annotations supported by salesforce :
@Deprecated:
            Use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, or variables that can no longer be referenced in subsequent releases of the managed package in which they reside. This is useful when you are re-factoring code in managed packages as the requirements evolve. New subscribers cannot see the deprecated elements, while the elements continue to function for existing subscribers and API integrations.
@Future:
            Use the future annotation to identify methods that are executed asynchronously. When you specify future, the method executes when Salesforce has available resources.
            To test methods defined with the future annotation, call the class containing the method in a startTest, stopTest code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.
@IsTest:           
            Use the isTest annotation to define classes or individual methods that only contain code used for testing your application. The isTest annotation is similar to creating methods declared as testMethod.
@ReadOnly:           
            The @ReadOnly annotation allows you to perform unrestricted queries against the Force.com database. All other limits still apply. It's important to note that this annotation, while removing the limit of the number of returned rows for a request, blocks you from performing the following operations within the request: DML operations, calls to System.schedule, calls to methods annotated with @future, and sending emails.

@RemoteAction:           
            The RemoteAction annotation provides support for Apex methods used in Visualforce to be called via JavaScript. This process is often referred to as JavaScript remoting.

@TestVisible:           
            Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive access level for running tests only.

Apex REST annotations:

@RestResource(urlMapping='/yourUrl'):
            The @RestResource annotation is used at the class level and enables you to expose an Apex class as a REST resource.
@HttpDelete:
            The @HttpDelete annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP DELETE request is sent, and deletes the specified resource.
@HttpGet:
            The @HttpGet annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP GET request is sent, and returns the specified resource.
@HttpPatch:
            The @HttpPatch annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP PATCH request is sent, and updates the specified resource.
@HttpPost:
            The @HttpPost annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP POST request is sent, and creates a new resource.
@HttpPut:
            The @HttpPut annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP PUT request is sent, and creates or updates the specified resource.

More Salesforce Interview Questions and Answers: