Friday, 15 December 2017

APEX Interview Questions


1. How can you done changes in apex trigger direct in production?
This is not possible direct in production first you need to done changes in sandbox then deploy it to production.

2. When should you build solutions declaratively instead of with code?
As a salesforce best practice, if something can be done using Configurations (Declarative) then its preferred over coding. The declarative framework is optimized for the platform and is always preffered.

3. Explain how MVC architecture fit for Salesforce?
In salesforce, Apex Classes works as Controllers, Visualforce Pages works as View and Custom objects works as Model.

4. Explain Apex Data Types?
Apex primitive data types include
• String
• Blob (for storing binary data)
• Boolean
• Date, DateTime and Time
• Integer, Long, Decimal, Double
• ID (Force.com database record identifier)

Example:
• DateTime dt = System.now() + 1;
• Boolean isClosed = true;
• String sCapsFirstName = ‘Andrew’.toUpperCase();

Apex sObject Types
Sobject (object representing a Force.com standard or custom object)

Example:
• Account acct = new Account(); //Sobject example

Apex has the following types of collections
• Lists
• Maps
• Sets

Example:
• List myList = new List();
• myList.add(12); //Add the number 12 to the list
• myList.get(0); //Access to first integer stored in the List

Enums
• Enum (or enumerated list) is an abstract that stores one value of a finite set of specified identifiers.
• To define an Enum, use enum keyword in the variable declaration and then define the list of values.
• By creating this Enum, you have created a new data type called Season that can be used as any other data type.

Example:
• public enum Season {WINTER, SPRING, SUMMER, FALL}

5. Explain Apex Variables?
Local variables are declared with Java-style syntax.
For example:
• Integer i = 0;
• String str;
• Account a;
• Account[] accts;
• Set s;
• Map m;

6. Apex and java similarties and differences?
Apex vs. Java: Similarties

• Both have classes, inheritance, polymorphism, and other common OOP features.
• Both have the same name variable, expression, and looping syntax.
• Both have the same block and conditional statement syntax.
• Both use the same object, array, and comment notation.
• Both are compiled, strongly-typed, and transactional.

Apex vs. Java: Differences

• Apex runs in a multi-tenant environment and is very controlled in its invocation and governor limits.
• To avoid confusion with case-insensitive SOQL queries, Apex is also case-insensitive.
• Apex is on-demand and is compiled and executed in cloud.
• Apex is not a general-purpose programming language but is instead a proprietary language used for specific business logic functions.
• Apex requires unit testing for development into a production environment.

7. Explain what is Trigger?
Trigger is a code that is executed before or after the record is updated or inserted.

8. When we Use a Before Trigger and After Trigger?
use "before" triggers to validate data or update fields on the same object.
use "after" triggers to update parent or related records.

9. If salesforce allow use to update the same object or validate the same object using before and after both trigger event so why before trigger exist?
If any thing is possible in same object without Soql using before trigger event so why we go for a after trigger event.

10. What is the maximum batch size in a single trigger execution?
Default batch size is 200 ,However maximum batch size is 2000.

11. If one object in salesforce have 2 triggers which runs “before Insert”. Is there any way to control the sequence of execution of these triggers?
Salesforce.com has documented that trigger sequence cannot be predefined. As a best practice create one trigger per object and use comment blocks to separate different logic blocks.

12. What are the trigger context variables?
To capture the runtime information we use trigger context variables.

Below context variables will return either true or false.
Trigger.isBefore (returns true if the trigger context is Before Mode)
Trigger.isAfter (returns true if the trigger context is After Mode)
Trigger.isInsert (returns true if the trigger context is Insert)
Trigger.isUpdate (returns true if the trigger context is Update)
Trigger.isDelete (returns true if the trigger context is Delete)
Trigger.isUndelete (returns true if the trigger context is Undelete)
Trigger.isExecuting (returns true if the apex class method is getting call from Apex Trigger)

Below context variables will store records at runtime.
trigger.old (stores history (old versions) of the records.)
trigger.oldMap (stores history (old versions) of the records along with id.)
trigger.new (stores new version of the records.)
trigger.newMap (stores new version of the records along with id.)

13. 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.

14. 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.

15. What Is The Difference Between Trigger.new And Trigger.old In Apex – Sfdc?
Trigger.new:

Returns a list of the new versions of the sObject records
Note that this sObject list is only available in insert and update triggers
i.e., Trigger.new is available in before insert, after insert, before update and after update
In Trigger.new the records can only be modified in before triggers.

Trigger.old:

Returns a list of the old versions of the sObject records
Note that this sObject list is only available in update and delete triggers.
i.e., Trigger.old is available in after insert, after update, before delete and after update.

16. What is the difference between trigger.new and trigger.newmap?
Trigger.new returns a list of the new versions of the sObject records.

Trigger.newMap returns a list of the new versions of the sObject records with the ids.

17. How to run trigger asynchronuosly?
If you use @future method trigger will run asynchronously.

18.What is the best practice of trigger?
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

2. Logic-less Triggers
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.

3. Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers

4. Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5. Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6. 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

7. 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 query more

8. Use @future Appropriately
It is critical to writing your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9. Avoid Hardcoding IDs When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail.

19. In which sequence trigger and automation rules run in Salesforce.com?
The following is the order salesforce logic is applied to a record.

1. Old record loaded from database (or initialized for new inserts)
2. New record values overwrite old values
3. System Validation Rules
4. All Apex “before” triggers (EE / UE only)
5. Custom Validation Rules
6. Record saved to database (but not committed)
7. Record reloaded from database
8. All Apex “after” triggers (EE / UE only)
9. Assignment rules
10.Auto-response rules
11.Workflow rules
12.Escalation rules
13.Parent Rollup Summary Formula value updated (if present)
14.Database commit
15.Post-commit logic (sending email)

Additional notes: There is no way to control the order of execution within each group above.

20. what are the access modifiers in apex?
• Classes have different access levels depending on the keywords used in the class definition.
– global: this class is accessible by all Apex everywhere.
• All methods/variables with the web service keyword must be global.
• All methods/variables dealing with email services must be global.
• All methods/variables/inner classes that are global must be within a global class to be accessible.
– public: this class is visible across your application or namespace.
– private: this class is an inner class and is only accessible to the outer class, or is a test class.
• Top-Level (or outer) classes must have one of these keywords.
– There is no default access level for top-level classes.
– The default access level for inner classes is private.
– protected: this means that the method or variable is visible to any inner classes in the defining Apex class. You can only use this access modifier for instance methods and member variables.

21. In How Many Ways We Can Invoke The Apex Class?
1. Visualforce page
2. Trigger
3. Web Services
4. Email Services
5. Process Builder

22. What is the difference between with sharing and without sharing?
With sharing Keyword: This keyword enforces sharing rules that apply to the current user. If absent, code is run under default system context. Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. Use With Sharing when the User has access to the records being updated via Role, Sharing Rules, Sales Teams – any sort of sharing really.

Example:

public with sharing class sharingClass {

// Code here

}

Without sharing keyword: Ensures that the sharing rules of the current user are not enforced. Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not enforced. For example, you may want to explicitly turn off sharing rule enforcement when a class acquires sharing rules when it is called from another class that is declared using with sharing. Without Sharing is reserved for cases where the User does not have access to the records, but there is a need to update them based on user input.

public without sharing class noSharing {

// Code here

}

Some things to note about sharing keywords:

The sharing setting of the class where the method is defined is applied, not of the class where the method is called. For example, if a method is defined in a class declared with with sharing is called by a class declared with without sharing, the method will execute with sharing rules enforced. If a class isn’t declared as either with or without sharing, the current sharing rules remain in effect. This means that the class doesn’t enforce sharing rules except if it acquires sharing rules from another class. For example, if the class is called by another class that has sharing enforced, then sharing is enforced for the called class. Both inner classes and outer classes can be declared as with sharing. The sharing setting applies to all code contained in the class, including initialization code, constructors, and methods. Inner classes do not inherit the sharing setting from their container class. Classes inherit this setting from a parent class when one class extends or implements another.

23. What are setter and getter methods?
Getter and Setter methods in salesforce are used to pass data from controller to visualforce and vice versa.

setter method value will be passed from visualforce page to controller ( Apex class) and same can be retrieved back to visualforce page through controller getter method.

24. How do you reffer to current page id in apex?
apexpages.currentpage().getparameters().get('id')

25. What is difference between WhoId and WhatId in the Data Model of Task ?
WhoID refers to people things. i.e. Lead ID or a Contact ID.

WhatID refers to object type things. i.e. Account ID or an Opportunity ID so on.

26. What Is The Difference Between Soql And Sosl?
SOQL ( Salesforce Object Query Language)
Only one object at a time can be searched
Query all type of fields
It can be used in triggers and classes
DML operation can be performed on query results

SOSL (Salesforce Object Search Language)
Many objects can be searched at a time
Query only e-mail, phone and text
It can be used in classes but not in triggers
DML operation cannot be performed on search result

27. I have 1 parent(account) and 1 child(contact),how will you get First Name,Last Name from child and email from the parent when Organization name in account is “CTS”?
SELECT Email, (SELECT FirstName, LastName FROM Contacts) FROM account WHERE Organization_Name = ‘CTS’.

28. Explain Difference In Count() And Count(fieldname) In Soql.?
COUNT()

COUNT() must be the only element in the SELECT list.
You can use COUNT() with a LIMIT clause.
You can’t use COUNT() with an ORDER BY clause. Use COUNT(fieldName) instead.
You can’t use COUNT() with a GROUP BY clause for API version 19.0 and later. Use COUNT(fieldName) instead.

COUNT(fieldName)

You can use COUNT(fieldName) with an ORDER BY clause.
You can use COUNT(fieldName) with a GROUP BY clause for API version 19.0 and later.

29. Which SOQL statement can be used to get all records even from recycle bin or Achieved Activities?
We will need “ALL Rows” clause of SOQL.
SELECT COUNT() FROM Contact WHERE AccountId = a.Id ALL ROWS

30. How can you lock record using SOQL so it cannot be modified by other user?
we will need “FOR UPDATE” clause of SOQL.
Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];

31. Difference between insert/update and Database.insert/ Database.update?
insert/update
Assume that you are inserting 100 records. If any one of the record fail due to error then entire operation will fail. None of the records will be saved into the database.

Database.insert/Database.update
Assume that you are inserting 100 records. If any one of the record fail due to error then it will perform partial operation (valid records will be inserted/updated) if we use Database.insert(list,false)/ Database.update(list,false).

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

33. Write a sample aggregate query or explain how to write a aggregate queries?
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’);

34. Some known governor limits in salesforce.com?
Total number of SOQL queries issued: 100
Total number of records retrieved by SOQL queries; 50,000
Total number of records retrieved by Database.getQueryLocator: 10,000
Total number of SOSL queries issued: 20
Total number of records retrieved by a single SOSL query: 2,000
Total number of DML statements issued: 150
Total number of records processed as a result of DML statements, Approval.process, or database.emptyRecycleBin: 10,000
Total stack depth for any Apex invocation that recursively fires triggers due to insert, update, or delete statements: 16
Total number of callouts (HTTP requests or Web services calls) in a transaction: 100
Maximum cumulative timeout for all callouts (HTTP requests or Web services calls) in a transaction: 120 seconds
Maximum number of methods with the future annotation allowed per Apex invocation: 50
Maximum number of Apex jobs added to the queue with System.enqueueJob: 50
Total number of sendEmail methods allowed: 10
Total heap size: 6 MB
Maximum CPU time on the Salesforce servers: 10,000 milliseconds
Maximum execution time for each Apex transaction: 10 minutes
Maximum number of push notification method calls allowed per Apex transaction: 10
Maximum number of push notifications that can be sent in each push notification method call: 2,000


35. Can we create 2 opportunities while the Lead conversion ?
Yes using Apex code.

36. Other than Soql and Sosl what is other way to get custom Settings?
Other than SOQL or SOSL, Custom settings have their own set of methods to access the record.

For example:If there is custom setting of name ISO_Country,

SO_Country__c code = ISO_Country__c.getInstance(‘INDIA’);

//To return a map of data sets defined for the custom object (all records in the custom object), //you would use:

Map mapCodes = ISO_Country__c.getAll();

// display the ISO code for India

System.debug(‘ISO Code: ‘+mapCodes.get(‘INDIA’).ISO_Code__c);

//Alternatively you can return the map as a list:

List listCodes = ISO_Country__c.getAll().values();

37. How to get all the fields of Sobject using dynamic apex?
Map m = Schema.getGlobalDescribe() ;

Schema.SObjectType s = m.get('API_Name_Of_SObject') ;

Schema.DescribeSObjectResult r = s.getDescribe() ;

Map fields = r.fields.getMap();

38. What Are Global Variables Explain With Examples?
Global variables are the variables used to reference the general information about the current user or your organization on a page.

Example:

Global variables must be referenced using Visualforce expression syntax to be evaluated, for example, {!$User.Name}.

List of available global variables are as below:

1. $Action
2. $Api
3. $Component
4. $ComponentLabel
5. $CurrentPage
6. $Label
7. $Label.Site
8. $ObjectType
9. $Organization
10. $Page
11. $Profile
12. $Resource
13. $SControl
14. $Setup
15. $Site
16. $User
17. $UserRole
18. $System.OriginDateTime
19. $ User.UITheme and $User.UIThemeDisplayed

39. What is Wrapper Class?
A Wrapper class is a class whose instances are collection of other objects.

It is used to display different objects on a Visual Force page in same table.

40. What are the effects of using the transient keyword?
The transient key word prevents the data from being saved into the view state. This should be used for very temporary variables.

41. Can you please give some information about Implicit and Explicit Invocation of apex?
Triggers - Implicit
Javascript remoting - Explicit

42. Can you give me situation where we can use workflow rather than trigger?
As i mention in question number 2 salesforce best practice is, if something can be done using Configurations (Declarative) then its preferred over coding.

If any thing we need to perform in same object we should go for a workflow rule and in case of master detail relationship we also update child to parent.

43. What is difference between public and global class in Apex ?
Public class can be accessed within application or namespace. This is not exactly like public modifier in Java.
Global class visible everywhere, any application or namespace. WebService must be declared as Global and which can be accessed inside Javascript also. It is like public modifier in Java.

44. Explain Considerations for Static keyword in Apex?
Apex classes cannot be static.
Static allowed only in outer class.
Static variables not transferred as a part of View State.
Static variables and static block runs in order in which they are written in class.
Static variables are static only in scope of request.

45. What is the use of save point in java script?
This will use for the rollback changes.

46. How many types of email services in salesforce? Write a apex code to send a email?
Their are two types of email services in salesforce

1. Inbound Email Services.
2. Outbound Email Services.

Sample code snippet to send an email using apex code

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[]{‘talk2srikrishna@gmail.com’};
mail.setToAddress(toAddresses);
mail.setSubject(‘Sample Mail Subject’);
mail.setPlainTextBody(‘Hello World!’);
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});

47. How can we hard delete a record using a Apex class/by code?
ALL ROWS keyword 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 dContactList=[Select ID From Contact Where IsDeleted = true limit 199 ALL ROWS];
Database.emptyRecycleBin( dContactList );

48. 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.

49. Syntax of testMethod?
@isTest
private class MyTestClass {

static testMethod void myTest1() {
}

static testMethod void myTest2() {
}

}

50. 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.

51. 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().

52. 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().

53. What are the assert statements?
To compare Actual value and Expected value we use assert statements.

Types of assert statements

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

54. 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())

55. 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 the variable is private we can access the test class.

56. What is the test class best practice?
1. Test class must start with @isTest annotation if class version is more than 25.
2. Test environment support @testVisible, @testSetUp as well.
3. Unit test is to test particular piece of code working properly or not.
4. Unit test method takes no argument, commit no data to database, send no email, flagged with testMethod keyword.
5. To deploy to production at-least 75% code coverage is required.
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit.
9. We should not focus on the percentage of code coverage, we should make sure that every use case should be covered including positive, negative, bulk and single record. Single Action -To verify that the single record produces the correct an expected result. Bulk action -Any apex record trigger, class or extension must be invoked for 1-200 records. Positive behavior: Test every expected behavior occurs through every expected permutation, I,e user filled out every correct data and not go past the limit. Negative Testcase: -Not to add future date, Not to specify the negative amount. Restricted User: -Test whether a user with restricted access used in your code. 10. Test class should be annotated with @isTest.
11 . @isTest annotation with test method is equivalent to testMethod keyword.
12. Test method should static and no void return type.
13. Test class and method default access is private , no matter to add access specifier.
14. classes with @isTest annotation can't be an interface or enum.
15. Test method code can't be invoked by non-test request.
16. Stating with Salesforce API 28.0 test method cannot reside inside nontest classes.
17. @Testvisible annotation to make visible private methods inside test classes.
18. The test method cannot be used to test web-service call out. Please use callout mock.
19. You can't send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true).
21. SeeAllData=true will not work for API 23 version earlier.
22. Accessing static resource test records in test class e,g List accList=Test.loadData(Account,SobjectType,resource name').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit.
24. @testSetup to create test records once in a method and use in every test method in the test class.
25. We can run unit test by using Salesforce Standard UI,Force.com IDE , Console , API.
26. Maximum number of test classes run per 24 hours of period is not greater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing is not taken into account. So we need to use a system.runAs to enforce record sharing.
28. System.runAs will not enforce user permission or field level permission.
29. Every test to runAs count against the total number of DML issued in the process.

57. What is Asynchronous Apex?
In a nutshell, asynchronous Apex is used to run processes in a separate thread, at a later time.

An asynchronous process is a process or function that executes a task "in the background" without the user having to wait for the task to finish.

Here’s a real-world example. Let’s say you have a list of things to accomplish before your weekly Dance Dance Revolution practice. Your car is making a funny noise, you need a different color hair gel and you have to pick up your uniform from your mom’s house. You could take your car to the mechanic and wait until it is fixed before completing the rest of your list (synchronous processing), or you could leave it there and get your other things done, and have the shop call you when it’s fixed (asynchronous processing). If you want to be home in time to iron your spandex before practice, asynchronous processing allows you to get more stuff done in the same amount of time without the needless waiting.

58. What is batch apex?
Batch Apex is used to run large jobs (think thousands or millions of records!) that would exceed normal processing limits. Using Batch Apex, you can process records asynchronously in batches (hence the name, “Batch Apex”) to stay within platform limits. If you have a lot of records to process, for example, data cleansing or archiving, Batch Apex is probably your best solution.

59. Write a syntax and structure of batch class?
Sample class

global class MyBatchClass implements Database.Batchable {

global (Database.QueryLocator | Iterable) start(Database.BatchableContext bc) {
// collect the batches of records or objects to be passed to execute
}

global void execute(Database.BatchableContext bc, List

records){
// process each batch of records
}

global void finish(Database.BatchableContext bc){
// execute any post-processing operations
}

}

Below code will call the batch class

BatchDemo bd = new BatchDemo();
database.executebatch(bd);

60. Suppose we have a batch size of 20 and we have 50 records so how many times each methods calls in batch class ?
Start method call at once.
Execute method call at three time.
Finish method call at once

61. Is it possible to call batch class from one more batch class?
Yes, it is possible, starting with Apex saved using Salesforce API version 26.0, you can call Database.executeBatch or System.scheduleBatch from the finish method. This enables you to start or schedule a new batch job when the current batch job finishes.

For previous versions, you can’t call Database.executeBatch or System.scheduleBatch from any batch Apex method. Note that the version used is the version of the running batch class that starts or schedules another batch job. If the finish method in the running batch class calls a method in a helper class to start the batch job, the Salesforce API version of the helper class doesn’t matter.

62. Is it possible to call future method from a batch class?
We cannot call one asynchronous process from another asynchronous process.

Since @future method and Batch Class both are asynchronous we cannot call a future method from the batch class or we cannot call a batch class from the future method.

63. How many batch jobs can be active/queued at a time?
Up to 5 batch jobs can be queued or active.

64. Is it possbile to write batch class and schedulable class in a same class?
By implementing Database.Batchable and Schedulable interfaces we can implement the methods in a same class.

Though it is possible it is not recommended to write like this.

65. What is Future method?
Future method is used to run processes in a separate thread, at a later time when system resources become available.

66. What is future method syntax? And some use cases of future methods?
global class SomeClass {
@future
public static void someFutureMethod(List recordIds) {
List accounts = [Select Id, Name from Account Where Id IN :recordIds];
// process account records to do awesome stuff
}
}

Callouts to external Web services. If you are making callouts from a trigger or after performing a DML operation, you must use a future or queueable method. A callout in a trigger would hold the database connection open for the lifetime of the callout and that is a "no-no" in a multitenant environment.
Operations you want to run in their own thread when time permits such as some sort of resource-intensive calculation or processing of records.
Isolating DML operations on different sObject types to prevent the mixed DML error. This is somewhat of an edge-case but you may occasionally run across this issue. See sObjects That Cannot Be Used Together in DML Operations for more details.

67. Explain few considerations for @Future annotation in Apex?
Method must be static
Cannot return anything ( Only Void )
To test @future methods, you should use startTest and stopTest to make it synchromouse inside Test class.
Parameter to @future method can only be primitive or collection of primitive data type.
Cannot be used inside VF in Constructor, Set or Get methods.
@future method cannot call other @future method.

68. In an apex invocation how many methods that we can write as future annotations?
10

69. What is Queueable Class?
Released in Winter '15, Queueable Apex is essentially a superset of future methods with some extra #awesomesauce. We took the simplicity of future methods and the power of Batch Apex and mixed them together to form Queueable Apex! It gives you a class structure that the platform serializes for you, a simplified interface without start and finish methods and even allows you to utilize more than just primitive arguments! It is called by a simple System.enqueueJob() method, which returns a job ID that you can monitor. It beats sliced bread hands down!

70. What is Queueable Class Syntax? And some additional benefits over future methods?
public class SomeClass implements Queueable {
public void execute(QueueableContext context) {
// awesome code here
}
}

Non-primitive types: Your Queueable class can contain member variables of non-primitive data types, such as sObjects or custom Apex types. Those objects can be accessed when the job executes.
Monitoring: When you submit your job by invoking the System.enqueueJob method, the method returns the ID of the AsyncApexJob record. You can use this ID to identify your job and monitor its progress, either through the Salesforce user interface in the Apex Jobs page or programmatically by querying your record from AsyncApexJob.
Chaining jobs: You can chain one job to another job by starting a second job from a running job. Chaining jobs are useful if you need to do some sequential processing.

71. What is Scheduled Class? And syntax of Scheduled Class?
The Apex Scheduler lets you delay execution so that you can run Apex classes at a specified time. This is ideal for daily or weekly maintenance tasks using Batch Apex.

global class SomeClass implements Schedulable {
global void execute(SchedulableContext ctx) {
// awesome code here
}
}

The class implements the Schedulable interface and must implement the only method that this interface contains, which is the execute method.

72. What are different API in Salesforce.com?
REST API:
REST API provides a powerful, convenient, and simple REST-based Web services interface for interacting with Salesforce. Its advantages include ease of integration and development, and it’s an excellent choice of technology for use with mobile applications and Web projects. However, if you have a large number of records to process, you may wish to use Bulk API, which is based on REST principles and optimized for large sets of data.

SOAP API:
SOAP API provides a powerful, convenient, and simple SOAP-based Web services interface for interacting with Salesforce.You can use SOAP API to create, retrieve, update, or delete records. You can also use SOAP API to perform searches and much more. Use SOAP API in any language that supports Web services.
For example, you can use SOAP API to integrate Salesforce with your organization’s ERP and finance systems, deliver real-time sales and support information to company portals, and populate critical business systems with customer information.

Chatter API:
Chatter API is a REST API that provides programmatic access to Chatter feeds and social data such as users, groups, followers, and files. It's used by developers who want to integrate Chatter into a variety of applications such as mobile applications, intranet sites, and third-party Web applications. Chatter API is similar to APIs offered by other companies with feeds, such as Facebook and Twitter. Its advantages include ease of integration and development.

Bulk API:
Bulk API is based on REST principles and is optimized for loading or deleting large sets of data. You can use it to query, insert, update, upsert, or delete a large number of records asynchronously by submitting batches which are processed in the background by Salesforce.
SOAP API, in contrast, is optimized for real-time client applications that update small numbers of records at a time. Although SOAP API can also be used for processing large numbers of records, when the data sets contain hundreds of thousands of records, it becomes less practical. Bulk API is designed to make it simple to process data from a few thousand to millions of records.
The easiest way to use Bulk API is to enable it for processing records in Data Loader using CSV files. This avoids the need to write your own client application.

Metadata API:
Use Metadata API to retrieve, deploy, create, update, or delete customizations for your organization. The most common use is to migrate changes from a sandbox or testing organization to your production environment. Metadata API is intended for managing customizations and for building tools that can manage the metadata model, not the data itself.
The easiest way to access the functionality in Metadata API is to use the Force.com IDE or Force.com Migration Tool. These tools are built on top of Metadata API and use the standard Eclipse and Ant tools respectively to simplify the task of working with Metadata API. Built on the Eclipse platform, the Force.com IDE provides a comfortable environment for programmers familiar with integrated development environments, allowing you to code, compile, test, and deploy all from within the IDE itself. The Force.com Migration Tool is ideal if you want to use a script or a command-line utility for moving metadata between a local directory and a Salesforce organization.

Streaming API:
Use Streaming API to receive notifications for changes to data that match a SOQL query that you define.
Streaming API is useful when you want notifications to be pushed from the server to the client. Consider Streaming API for applications that poll frequently. Applications that have constant polling action against the Salesforce infrastructure, consuming unnecessary API call and processing time, would benefit from this API which reduces the number of requests that return no data. Streaming API is also ideal for applications that require general notification of data changes. This enables you to reduce the number of API calls and improve performance.

Apex REST API:
Use Apex REST API when you want to expose your Apex classes and methods so that external applications can access your code through REST architecture. Apex REST API supports both OAuth 2.0 and Session ID for authorization.

Apex SOAP API:
Use Apex SOAP API when you want to expose your Apex methods as SOAP Web service APIs so that external applications can access your code through SOAP. Apex SOAP API supports both OAuth 2.0 and Session ID for authorization.

12 comments:

  1. 27th question answer need to improvise as on Dec 26th 2017.

    ReplyDelete
  2. Thanks Surya, This is Nice way to Explain.. Please explain with demo example in deep. It would be practically more beneficial to crack interview.

    ReplyDelete
  3. Hi there! I know this is somewhat off topic but I was wondering which blog platform are you using for this website? I'm getting sick and tired of Wordpress because I've had issues with hackers and I'm looking at alternatives for another platform. I would be fantastic if you could point me in the direction of a good platform.College Mathematics for Business test bank solutions manual

    ReplyDelete
  4. Worst set of questions for Salesforce

    ReplyDelete
  5. Good Post. I like your blog. Thanks for Sharing
    Salesforce Course in Gurgaon

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. Informative blog. Thank you for sharing with us..
    AWS Online Training

    ReplyDelete
  8. Salesforce Admin/Dev can mass Compare Multiple Profiles and export in single click in single xls sheet using Bulk Object Field Creator (BOFC) App.

    ReplyDelete