What is Apex?

Apex is a strongly typed, object-oriented programming language that compiles and run on force.com platform. Apex language has a syntax similar to java. Apex code can be executed on click of a button, weblinks, triggers, and visualforce pages. Apex is available in Enterprise, Performance, Unlimited, Developer, and Database.com Editions of Salesforce.

In this beginner Apex training, you will learn,

Features of Apex:

Here are important features of Apex:

  • Apex is a case insensitive language.
  • You can perform DML operations like INSERT, UPDATE, UPSERT, DELETE on sObject records using apex.
  • You can query sObject records using SOQL(salesforce object query language) and SOSL(salesforce object search language) in apex.
  • Allows you to create a unit test and execute them to verify the code coverage and efficiency of the code in apex.
  • Apex executes in a multi-tenant environment, and Salesforce has defined some governor limits that prevent a user from controlling the shared resources. Any code that crosses the salesforce governor limit fails, an error shows up.
  • Salesforce object can be used as a datatype in apex. For example -
    Account acc = new Account(); 
    ,here Account is a standard salesforce object.
  • Apex automatically upgrades with every Salesforce release.

When Should Developer Choose Apex:

Apex code should only be written if a business scenario is too complex and can't be implemented using the pre-built functionality provided by Salesforce.

Following are the few scenarios where we need to write apex code:

  • To create web services that integrate Salesforce with other applications.
  • To implement custom validation on sobjects.
  • To execute custom apex logic when a DML operation is performed.
  • To implement functionality that can't be implemented using existing workflows flows and process builders functionality.
  • To setup email services, you need to include processing the contents, headers, and attachments of email using apex code.

Working Structure Of Apex:

Following are the flow of actions for an apex code:

  • Developer Action: All the apex code written by a developer is compiled into a set of instructions that can be understood by apex runtime interpreter when the developer saves the code to the platform and these instructions then save as metadata to the platform.
  • End User Action: When the user event executes an apex code, the platform server gets the compiled instructions from metadata and runs them through the apex interpreter before returning the result.

Apex Syntax:

Variable Declaration:

As apex is strongly typed language, it is mandatory to declare a variable with datatype in apex.

For example

contact con = new contact(); 

here the variable con is declared with contact as a datatype.

SOQL Query:

SOQL stands for salesforce object query language. SOQL is used to fetch sObject records from Salesforce database. For example-

Account acc = [select id, name from Account Limit 1]; 

The above query fetches account record from salesforce database.

Loop Statement:

Loop statement is used to iterate over the records in a list. The number of iteration is equal to the number of records in the list. For example:

list<Account>listOfAccounts = [select id, name from account limit 100];
// iteration over the list of accounts
for(Account acc : listOfAccounts){
	//your logic
}

In the above snippet of code, listOfAccounts is a variable of list datatype.

Flow Control Statement:

Flow control statement is beneficial when you want to execute some lines of the code based on some conditions.

For example:

list<Account>listOfAccounts = [select id, name from account limit 100];
// execute the logic if the size of the account list is greater than zero
if(listOfAccounts.size() >0){
	//your logic
}

The above snippet of code is querying account records from the database and checking the list size.

DML statement:

DML stands for data manipulation language. DML statements are used to manipulate data in the Salesforce database. For example -

Account acc = new Account(Name = ‘ Test Account’);
Insert acc; //DML statement to create account record.

Apex Development Environment:

Apex code can be developed either in sandbox and developer edition of Salesforce.

It is a best practice to develop the code in the sandbox environment and then deploys it to the production environment.

Apex code development tools: Following are the three tools available to develop apex code in all editions of Salesforce.

  • Force.com Developer Console
  • Force.com IDE
  • Code Editor in the Salesforce User InterfaceYou

Data Type In Apex:

Following are the datatypes supported by apex:

Primitive:

Integer, Double, Long, Date, Date Time, String, ID, and Boolean are considered as primitive data types.All primitive data types are passed by value, not by reference.

Collections:

Three types of collection are available in Apex

  • List: It is an ordered collection of primitives, sObjects, collections, or Apex objects based on indices.
  • Set: An unordered collection of unique primitives.
  • Map: It is collection of unique, primitive keys that map to single values which can be primitives, sObjects, collections, or Apex objects.

sObject:

This is a special data type in Salesforce. It is similar to a table in SQL and contains fields which are similar to columns in SQL.

Enums

Enum is an abstract data type that stores one value of a finite set of specified identifiers

Classes

Objects :

It refers to any data type which is supported in Apex.

Interfaces

Apex Access Specifier:

Following are the access specifier supported by apex:

Public:

This access specifier gives access to a class, method, variable to be used by an apex within a namespace.

Private:

This access specifier gives access to a class, method, variable to be used locally or within the section of code, it is defined. All the technique, variables that do not have any access specifier defined have the default access specifier of private.

Protected:

This access specifier gives access to a method, variable to be used by any inner classes within defining Apex class.

Global:

This access specifier gives access to a class, method, variable to be used by an apex within a namespace as well as outside of the namespace. It is a best practice not to used global keyword until necessary.

Keywords in Apex:

With sharing:

If a class is defined with this keyword, then all the sharing rules apply to the current user is enforced and if this keyword is absent, then code executes under system context.

For Example:

public with sharing class MyApexClass{
// sharing rules enforced when code in this class execute
}

Without sharing:

If a class is defined with this keyword, then all the sharing rules apply to the current user is not enforced.

For Example:

public without sharing class MyApexClass{
// sharing rules is not enforced when code in this class execute
}

Static:

A variable, Method is defined with the static keyword is initialized once and associated with the class. Static variables, methods can be called by class name directly without creating the instance of a class.

Final:

A constant, Method is defined with the final keyword can't be overridden. For example:

public class myCls {
static final Integer INT_CONST = 10;
}

If you try to override the value for this INT_CONST variable, then you will get an exception - System.FinalException: Final variable has already been initialized.

Return:

This keyword returns a value from a method. For example:

public String getName() {
return  'Test' ;
}

Null:

It defines a null constant and can be assigned to a variable. For example

 Boolean b = null; 

Virtual:

If a class is defined with a virtual keyword, it can be extended and overridden.

Abstract:

If a class is defined with abstract keyword, it must contain at least one method with keyword abstract, and that method should only have a signature.

For example:

public abstract class MyAbstrtactClass {
abstract Integer myAbstractMethod1();
}

Apex String:

A string is a set of characters with no character limits. For example:

String name = 'Test';

There are several in-built methods provide by String class in salesforce. Following are the few frequently and mostly used functions:

abbreviate(maxWidth):

This method truncates a string to the specified length and returns it if the length of the given string is longer then specified length; otherwise, it returns the original string. If the value for maxWidth variable is less than 4, this method returns a runtime exception - System.StringException: Minimum abbreviation width is 4

For example:

String s = 'Hello World';
String s2 = s.abbreviate(8);
System.debug('s2'+s2); //Hello...

capitalize():

This method converts the first letter of a string to title case and returns it.

For example:

String s = 'hello;
String s2 = s.capitalize();
System.assertEquals('Hello', s2);

contains(substring):

This method returns true if the String calling the method contains the substring specified.

String name1 = 'test1';
String name2 = 'test2';
Boolean flag = name.contains(name2);
System.debug('flag::',+flag); //true

equals(stringOrId):

This method returns true if the parameter passed is not null and indicates the same binary sequence of characters as the string that is calling the method.

While comparing Id values the length of the ID's may not to be equal. For example: if a string that represents 15 characters id is compared with an object that represents 18 characters ID this method returns true. For example:

Id idValue15 = '001D000000Ju1zH';
Id idValue18 = '001D000000Ju1zHIAR';
Boolean result4 = stringValue15.equals(IdValue18);
System.debug('result4', +result4); //true

In the above example equals method is comparing 15 characters object Id to 18 characters object Id and if both these id represents the same binary sequence it will return true.

Use this method to make case-sensitive comparisons.

escapeSingleQuotes(stringToEscape):

This method adds an escape character (\) before any single quotation in a string and returns it. This method prevents SOQL injection while creating a dynamic SOQL query. This method ensures that all single quotation marks are considered as enclosing strings, instead of database commands.

For example:

String s = 'Hello Tom';
system.debug(s); // Outputs 'Hello Tom'
String escapedStr = String.escapeSingleQuotes(s);
// Outputs \'Hello Tom\'

remove(substring):

This method removes all the occurrence of the mentioned substring from the String that calls the method and returns the resulting string.

For example:

String s1 = 'Salesforce and force.com';
String s2 = s1.remove('force');
System.debug( 's2'+ s2);// 'Sales and .com'

substring(startIndex):

This method returns a substring starts from the character at startIndex extends to the last of the string.

For Example:

String s1 = 'hamburger';
String s2 = s1.substring(3);
System.debug('s2'+s2); //burger

reverse():

This Method reverses all the characters of a string and returns it. For example:

String s = 'Hello';
String s2 = s.reverse();
System.debug('s2::::'+s2);// olleH  // Hello

trim(): This method removes all the leading white spaces from a string and returns it.

valueOf(toConvert):

This method returns the string representation of passed in object.

Apex Governor Limits:

Apex governor limits are the limits enforced by apex runtime engine to ensure that any runway apex code and processes don't control the shared resources and don't violate the processing for other users on the multitenant environment. These limits are verified against each apex transaction. Following are the governor limits defined by salesforce on each apex transaction:

Description Limit
SOQL queries that can be done in a synchronous transaction 100
SOQL queries that can be done in an Asynchronous transaction 200
Records that can be retrieved by a SOQL query 50000
Records that can be retrieved by Database.getQueryLocator 10000
SOSL queries that can be done in an apex transaction 20
Records that can be retrieved by a SOSL query 2000
DML statements that can be done in an apex transaction 150
Records that can be processed as a result of a DML statement, Approval.process, or database.emptyRecycleBin 10000
Callouts that can be done in an apex transaction. 100
Cumulative timeout limit on all the callouts that are being performed in an apex transaction 120 seconds
Limit on apex jobs that can be added to the queue with System.enqueueJob 50
Execution time limit for each Apex transaction 10 minutes
Limit on characters that can be used in an apex class and trigger 1 million
CPU time limit for synchronous transaction 10,000 milliseconds
CPU time limit for asynchronous transaction 60,000 milliseconds

Apex Getter and Setter:

Apex property is similar to apex variable. Getter and setter are necessary to an apex property. Getter and setter can be used to execute code before the property value is accessed or changed. The code in the get accessor executes when a property value is read. The code in the set accessor runs when a property value is changed. Any property having get accessor is considered read-only, any property having set accessor is considered to write only any property having both get and set accessor is deemed to be read-write. Syntax of an apex property:

public class myApexClass {
// Property declaration
	access_modifierreturn_typeproperty_name {
	get {
			//code  
		}
		set{
			//code
		}
	}

Here, access_modifier is the access modifier of the property. return_type is the dataType of the property. property_name is the name of the property.

Below is an example of an apex property having both get and set accessor.

public class myApex{
	public String name{
		get{ return name;}
		set{ name = 'Test';}
	}
}

Here, the property name is name, and it's public property, and it is returning a string dataType.

It is not mandatory to have some code in the get and set block. These block can be left empty to define an automatic property. For example:

public double MyReadWriteProp{ get; set; } 

Get and set accessor can also be defined with their access modifier. If an accessor is defined with a modifier, then it overrides the access modifier for the property. For example:

public String name{private get; set;}// name is private for read and public to write.

Apex Class:

An apex class is a blueprint or template from which objects are created. An object is the instance of a class.

There are three ways of creating apex classes in Salesforce:

Developer Console

Force.com IDE

Apex class detail page.

In apex, you can define an outer class also called top-level class, and you can also define classes within an outer class called inner classes.

It is mandatory to use access modifier like global or public in the declaration of the outer class.

It is not necessary to use access modifier in the declaration of inner classes.

An apex class is defined using class keyword followed by the class name.

Extends keyword is used to extend an existing class by an apex class, and implements keyword is used to implement an interface by an apex class.

Salesforce apex doesn't support multiple inheritances, an apex class can only extend one existing apex class but can implement multiple interfaces.

An apex class can contain user-defined constructor, and if a user-defined constructor is not available, a default constructor is used. The code in a constructor executes when an instance of a class is created.

Syntax of an apex class:

public class myApexClass{
// variable declaration
//constructor
	public myApexClass{
	}
//methods declaration
}

The new keyword is used to create an instance of an apex class. Below is the syntax for creating an instance of a apex class.

myApexClass obj = new myApexClass();

Apex Trigger:

Apex triggers enable you to execute custom apex before and after a DML operation is performed.

Apex support following two types of triggers:

Before triggers: These triggers are used to validate and update the field's value before the record save to the database.

After triggers: These triggers are used to access the fields(record ID, LastModifiedDate field) set by the system after a record committed to the database. These fields value can be used to modify other records. Records that fires after triggers are read-only.

It is a best practice to write bulky triggers. A bulky trigger can process a single record as well as multiple records at a time.

Syntax of an apex trigger:

trigger TriggerName on ObjectName (trigger_events) {
	//Code_block
 }

Here, TriggerName is the name of the trigger, ObjectName is the name of the object on which trigger to be written, trigger_events is the comma-separated list of events.

Following are the events supported by the apex triggers: before insert, before the update, before delete, after insert, after an update, after delete, after undelete.

Static keywords can't be used in an Apex trigger. All the keywords applicable to inner classes can be used in an Apex trigger.

There are implicit variable define by every trigger that returns the run-time context. These variables are defined in the system. Trigger class. These variables are called context variables. Below screenshot shows the context variable supported by apex trigger.

Following are the consideration of the context variable in the apex trigger:

  • Don't use the trigger.new and trigger.old in DML operations.
  • Trigger.new can't be deleted.
  • Trigger.new is read-only.
  • Trigger.new can be used to changes the values of the fields on the same object in before trigger only.

Below screenshots list the considerations about specific actions in different trigger events.

Batch Class in Apex:

Batch class in salesforce is used to process a large number of records that would exceed the apex governor limits if processed normally. Batch class executes the code asynchronously.

Following are the advantages of batch class:

  • Batch class process the data in chunks and if a chunk fails to process successfully, all the chunks successfully processed do not roll back.
  • Every chunk of data in a batch class processed with a new set of governor limits which ensure that code executes within the governor execution limits.
  • Database. Batchable interface must be implemented by an apex class to be used as a batch class. It provides three methods which must be implemented by the batch class.

Following are the three methods provided by Database. Batchable interface:

1.start():

This method generates the scope of records or objects to be processed by the interface method execute. During the execution of batch, it is called once only. This method either returns a Database.QueryLocator object or an Iterable. The number of records retrieved by SQL query using the Database.QueryLocator object is 50 million records but using an iterable, the total number of records that can be retrieved by the SQL query is 50000 only. Iterable is used to generate complex scope for batch class.

Syntax of start method:

global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContextbc) {}

2.execute():

This method is used for the processing of each chunk of data. For each chunk of records execute method is called. The default batch size for execution is 200 records. Execute method takes two arguments:

A reference to the Database.BatchableContext object,

A list of sObjects, such as List<sObject>, or a list of parameterized types. Syntax of execute method:

global void execute(Database.BatchableContext BC, list<P>){}

3.finish():

The finish method is called once during the execution of the batch class. Post-processing operations can be performed in the finish method. For example: sending the confirmation email. This method is called when all the batch get processed. Syntax of Finish method:

global void finish(Database.BatchableContext BC){}

Database.BatchableContext object:

Each method of the Database. Batchable interface has a reference to Database.BatchableContext object.

This object is used to track the progress of the batch job.

Following are instance methods provided by BatchableContext :

  • getChildJobId(): This method returns the ID of a batch job that is currently processed.
  • getJobId(): This method returns the ID of the batch job.

Below is the syntax of a batch class :

global class MyBatchClass implements Database.Batchable<sObject> {
	global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContextbc) {
// collect the batches of records or objects to be passed to execute
}
global void execute(Database.BatchableContextbc, List<P> records){
// process each batch of records
}
global void finish(Database.BatchableContextbc){
// execute any post-processing operations
}
}

Database.executeBatch Method:

Database.executeBatch method is used for executing a batch class.

This method takes two parameters: Instance of the batch class to be processed, Options parameter to specify the batch size if not specified it takes the default size of 200.

Syntax of Database.executeBatch :

Database.executeBatch(myBatchObject,scope)

Executing a batch class name MyBatchClass :

MyBatchClassmyBatchObject = new MyBatchClass(); 
Id batchId = Database.executeBatch(myBatchObject,100);

Database.stateful :

Batch class is stateless by default. Every time the execute method is called a new copy of an object is received, all the variables of the class is initialized.

Database.stateful is implemented to make a batch class stateful.

If your batch class implemented the Database, stateful interface all the instance variable retain their values, but the static variables get reset between the transaction.

Summary:

  • Apex is a strongly typed, object-oriented apex programming language that compiles and run on force.com platform
  • Apex is a case insensitive language
  • Two types of flow of actions in Apex are 1) Developer action 2) End-user action
  • Apex helps you to create web services that integrate Salesforce with other applications.
  • Datatypes supported by apex are: 1).Primitive 2) Collections 3) sObject, Enums, 4) Classes, 5) Objects and Interfaces
  • Public, Private, Protected and Global are specified support by Apex
  • Keywords using in Apex are : 1) With Sharing, 2) Without sharing, 3) Static, 4) Final 5)Return, 6)Null, 7) Virtual, 8) Abstract
  • A string is a set of characters with no character limits
  • Apex governor limits are the limits enforced by apex runtime engine to ensure that any runway apex code and processes
  • Getter and setter can be used to execute code before the property value is accessed or changed
  • There are three ways of creating apex classes in Salesforce: 1)Developer Console 2)Force.com IDE and, 3) Apex class detail page.
  • Apex triggers enable you to execute custom apex before and after a DML operation is performed.
  • Batch class in salesforce is used to process a large number of records that would exceed the apex governor limits if processed normally.

 

YOU MIGHT LIKE: