Features of Apex Programming Language
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 emciency 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.
For example
–
Account acc = new Account();
here Account is a standard salesforce object.
Working Structure Of Apex
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
Now in this Apex programming tutorial, we will learn
about 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 Specifler
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 the Apex Class example:
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.
No comments:
Post a Comment