Regression Testing

APEX Tutorial: Apex Programming Class & Coding Examples

SalesForce Apex is an object-oriented and strongly typed programming language that was developed for the development of Software as as Service (SaaS) and Customer Relationship Management (CRM) applications (CRM). Providing back-end database support as well as client-server interfaces, Apex aids developers in the development of third-party SaaS applications as well as the incorporation of business logic into system events.

Apex enables developers to incorporate business logic into system events such as button clicks, related record updates, and Visualforce pages by using the Apex Object Model. Apex has a syntax that is similar to Java.

In this beginner Salesforce Apex tutorial, you will learn the fundamentals of Apex, including:

The following are some of the most important features of Salesforce Apex:

Apex is a language that does not care about case.
Using apex, you can perform DML operations on sObject records, such as INSERT, UPDATE, UPSERT, and DELETE on the records.
Salesforce object records can be queried using the SOQL (salesforce object query language) and SOSL (salesforce object search language) languages in Apex.
The ability to create unit tests and run them to verify the code coverage and efficiency of the code in Apex is provided by this feature.
Apex runs in a multi-tenant environment, and Salesforce has set some governor limits to prevent a user from having complete control over the shared resources in the environment. Any code that exceeds the salesforce governor limit will fail, and an error message will appear.
An object from Salesforce can be used as a datatype in Apex. Take the following example: Account acc = new Account(); in this case, Account is a standard salesforce entity.

When Should a Developer Consider Using Apex?

The use of Apex code should only be considered if a business scenario is too complex to be implemented using the pre-built functionality offered by Salesforce.

The following are a few examples of situations in which we must write Apex code:

To develop web services that will allow Salesforce to communicate with other applications.
To implement custom validation on sobjects, see Custom Validation.
When a DML operation is performed, it is possible to run custom apex logic.
For the purpose of implementing functionality that cannot be achieved through the use of existing workflow flows and process builders features.
Email services must be configured to include processing the contents, headers, and attachments of emails using Apex code in order to be effective.
Apex’s Organizational Structure
During this Apex tutorial, we will learn about the working structure of Apex, which includes:

For an apex code, the following is the sequence of actions:

Developer Action: When a developer saves apex code to the platform, all of the apex code written by the developer is compiled into a set of instructions that can be understood by the apex runtime interpreter. These instructions are then saved to the platform as metadata.
After the user event has finished executing an apex code, the platform server retrieves the compiled instructions from the metadata and runs them through the apex interpreter before returning the result.
Apex’s Organizational Structure
Apex’s Working Structure Apex Syntax Variable Declaration: Because apex is a strongly typed language, it is mandatory to declare a variable with a datatype when using apex.

As an illustration,

Here, the variable con is declared as a datatype of contact, and the function new contact is called on it.

SOQL Query: SOQL is an abbreviation for salesforce object query language (also known as SOQL). The SOQL query language is used to retrieve sObject records from the Salesforce database. As an illustration-

Account acc = [select id and name from Account Limit 1]; Account acc = [select id and name from Account Limit 1]
The query above retrieves a record for an account from the salesforce database.

When it comes to iterating over the records in a list, the loop statement comes in handy. The number of times the list is iterated is the same as the number of records in the list. As an illustration:

iteration over the list of accounts for(Account acc: listOfAccounts) /your logic listAccount>listOfAccounts = [select account id, name from account limit 100];
The listOfAccounts variable in the preceding snippet of code has the datatype of a list.

Flow Control Statement: Flow control statements are useful when you want to execute specific lines of code based on certain conditions.

As an illustration:

listAccount>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) if(listOfAccounts.size() >0) if(listOfAccounts.size() >0) if(listOfAccounts.size() >0)

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

An example of a DML statement: DML is an abbreviation for data manipulation language. Data manipulation statements (DML statements) are used to manipulate data in the Salesforce database. As an illustration –

Account acc = new Account(Name = ‘Test Account’); Account acc = new Account(Name = ‘Test Account’);
Insert acc; /DML statement to create a record for the account.
Apex Development Environment is a software development environment.
In this Apex programming tutorial, we will learn about the Apex Development Environment, which includes the following:

Developers can work on Apex code in both the sandbox and developer editions of the Salesforce platform.

Development of code in a sandbox environment and subsequent deployment of the code to the production environment is considered best practise.

Apex code development tools include the following: The following are the three tools that are available for developing apex code in all Salesforce editions.

Force.com Developer Console is a web-based application that allows you to develop applications for Force.com.
The Force.com IDE Code Editor is accessible through the Salesforce User Interface.
Apex recognises your data type.
Data types supported by Apex include the ones listed below:

Primitive data types include integers, doubles, longs, dates, dates times, strings, IDs, and Booleans, among others.

Rather than passing by reference, all primitive data types are passed by value.

There are three different types of collections available in Apex.

The term “list” refers to an ordered collection of primitive objects (such as sObjects), collections, or Apex objects that are organised according to their indexes.
Set: An unordered collection of primitives that are all the same.
Map: A map is a collection of unique, primitive keys that map to single values that can be primitives, sObjects, collections, or Apex objects. A map is a collection of primitive keys that map to primitive values.
sObject: This is a special data type in Salesforce that is used to store objects. It is analogous to a table in SQL, and it contains fields that are analogous to columns in SQL as well.

Enums
Enum is an abstract data type that stores a single value from a finite set of identifiers that have been specified in advance.

Classes

Objects: This term refers to any data type that is supported by Apex, including strings.

Interfaces

Apex Access Specifier is a type of access specification.
The following are examples of access specifiers that are supported by apex:

The public access specifier allows an apex within a namespace to have access to a class, method, or variable that has been designated as public.

The private access specifier allows a class, method, or variable to be used only locally or within the section of code in which it is declared. All of the technique and variable names that do not have an access specifier defined have the access specifier private as their default access specifier.

Protected: This access specifier grants access to a method or variable that can be used by any inner classes that are contained within the defining Apex class.

A class, method, or variable that is used by an apex within a namespace as well as outside of the namespace is granted access using the global access specifier. It is recommended that you avoid using global keywords unless absolutely necessary.

Apex has keywords that you can use.
The keyword “with sharing” indicates that if a class is defined with this keyword, then all sharing rules that apply to the current user are enforced; if this keyword is not present, code is executed in the system’s context.

As an illustration:

public with a class for sharing MyApexClass / when code in this class is executed, the sharing rules are enforced by the system.
Without revealing anything:
When this keyword is used to define a class, it means that all of the sharing rules that apply to the current user are not enforced.

As an illustration:

public without revealing their class MyApexClass / When code in this class is executed, the sharing rules are not enforced.
When the static keyword is used to define a variable, it is only initialised once and associated with the class it is defined in. Static variables and methods can be accessed directly by class name, without the need to create an instance of the class.

Finally, the final keyword defines a constant, which means that the method can’t be overridden. As an illustration:

INT CONST = 10; public class myCls INT CONST = 10; static final Integer INT CONST = 10;
If you attempt to override the value of the INT CONST variable, you will receive an exception with the message System.
FinalException: The final variable has already been initialised before throwing this exception.

Return: This keyword indicates that a method has returned a value. As an illustration:

public String getName() returns the string ‘Test’; ;
Null: This keyword defines a null constant that can be assigned to a variable in a programme. As an illustration,

A virtual keyword is used to define a class that can be extended and overridden. The value of the virtual keyword is null.

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

As an illustration:

public abstract class is a type of public abstract class MyAbstrtactClass consists of an abstract Integer. myAbstractMethod1(); \s}
Apex Strings are a type of string that can be used to represent a mathematical expression.
A string is a collection of characters that has no restriction on the number of characters it can contain. As an illustration:

Test string name = ‘Test’; The String class in salesforce has a number of built-in methods that can be utilised. The following are a few of the most frequently and frequently used functions:

When a string is longer than the specified length, this method truncates it and returns it; otherwise, the original string is returned. abbreviate(maxWidth): This method truncates a string to the specified length and returns it if the length of the given string is longer than the specified length; otherwise, it returns the original string. If the value of the maxWidth variable is less than 4, this method throws a runtime exception – System – as a result. StringException: The abbreviation width must be at least four characters.

As an illustration:

The string s equals ‘Hello, World’; the string s2 equals s.abbreviate(8); the string System.debug(‘s2’+s2); the string s = ‘Hello, World’ /Hello… \scapitalize():
This method converts the first letter of a string to title case and returns the result of the conversion.

As an illustration:

The string s equals ‘hello; the string s2 equals s.capitalize(); the string System.assertEquals(‘Hello’, s2); the string contains(substring):
This method returns true if the substring specified in the call to the method is contained within the String calling the method.

The strings name1 and name2 are equal to ‘test1’ and ‘test2’, respectively; the Boolean flag is equal to name.contains(name2);
System.debug(‘flag::’,+flag); /true \sequals(stringOrId):
Whether or not the passed parameter is null and indicates the same binary sequence of characters as the string that is calling the method is determined by the method’s return value.

When comparing ID values, keep in mind that the length of the IDs may not be the same. When a string with ID of 15 characters is compared to an object with ID of 18 characters, this method returns true in this example. As an illustration:

Id idValue15 = ‘001D000000Ju1zH’; Id idValue18 = ‘001D000000Ju1zHIAR’; Boolean result4 = stringValue15.equals(IdValue18); Id idValue15 = ‘001D000000Ju1zH’; Id idValue18 = ‘001D000000Ju1
System.debug(‘result4’, +result4) is a debugging function.
; /true
As shown in the preceding example, the equals method is comparing two 15-character object IDs to an 18-character object Id, and if both of these ids represent the same binary sequence, the equals method will return true.

When making case-sensitive comparisons, this method should be used.

escapeSingleQuotes(stringToEscape): This method inserts an escape character () before any single quotation in a string and returns the result of that operation. While creating a dynamic SOQL query, this method prevents SOQL injection from occurring. This method ensures that all single quotation marks are treated as enclosing strings, rather than database commands, when evaluating a string.

As an illustration:

String s = ‘Hello Tom’; system.debug(s); / Produces the message ‘Hello Tom’
The string has been escaped
escapeSingleQuotes(s); / This method returns the string ‘Hello Tom’ remove(substring): This method removes all occurrences of the specified substring from a String that is being called by the method and returns the resulting string.

As an illustration:

String s1 = ‘Salesforce and force.com’; String s2 = s1.remove(‘force’); System.debug(‘s2’+ s2); String s3 = s1.remove(‘force’); String s4 = s1.remove(‘force’); String s5 = s1.remove(‘force’);

Substring (startIndex) for the phrase “Sales and.com”:
This method returns a substring that begins with the character at startIndex and ends with the last character of the string returned by the previous method.

As an illustration:

The string s1 represents the word “hamburger,” and the string s2 represents s1.substring(3); System.debug(“s2″+”s2”) represents the reverse of the word “hamburger.”
When a string is passed to this method, it is reversed and the result is returned. As an illustration:

In this example, the string s equals the word “Hello.” The string s2 equals the word “Hello,” and the system debug function is called with the string “s2:::” plus the string “Hello.”

/ olleH / olleH / Hello \strim(): This method takes a string and removes all of the leading white spaces before returning it.

valueOf(toConvert): This method returns a string representation of the object that was passed in as a parameter.

Apex Governor Sets a Time Limit
Runway apex code and processes must not control shared resources or violate the processing of other users in the multitenant environment. Apex governor limits are imposed by the apex runtime engine to ensure that this does not happen. Each apex transaction is subjected to a verification of these limits. Each apex transaction is subject to the governor limits set by salesforce, which are as follows:

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

Getter and setter for apex
Apex property is a type of variable that is similar to apex property. A getter and a setter are required for an apex property to function properly. The getter and setter methods can be used to execute code before the value of a property is accessed or modified. When the value of a property is read, the code in the get accessor is executed. When the value of a property is changed, the code in the set accessor is executed. Property with get accessor is considered read-only, property with set accessor is considered write-only, and property with both get and set accessors is considered read-write. Any property with both get and set accessor is considered read-write. The following is the syntax of an apex property:

The access modifier of the property is represented by the variable access modifier. The dataType of the property is represented by the return type. The name of the property is represented by the variable property name.

An example of an apex property that has both a get and a set accessor is shown below.

In this case, the property name is name, and it is a public property, and it returns a string dataType as its return value.

It is not required to have any code in the get and set blocks, but it is recommended. If you want to define an automatic property, you can leave this block empty. As an illustration:

double exposure in public MyReadWriteProp get; set; MyReadWriteProp get; set;

The accessors for get and set can also be defined in terms of their access modifiers. When an accessor is defined with a modifier, it takes precedence over the access modifier for the corresponding property. As an illustration:

public String name/private get; set;/ name is private for reading and public for writing; it is not case sensitive.

Apex Class is the highest level of achievement.

An apex class is a blueprint or template from which objects can be created in the following ways: A class is represented by an instance of the class.

Creating apex classes in Salesforce can be done in three different ways:

Console for Developers

Force.com Integrated Development Environment

The detail page for an Apex class.

It is possible to define an outer class in Apex, which is also known as a top-level class, as well as classes within an outer class, which are known as inner classes.

In the declaration of the outer class, it is mandatory to use an access modifier such as global or public to grant access to the class.

When declaring inner classes, it is not necessary to include the access modifier in the declaration.

The class keyword is used in conjunction with the class name to define an apex class.

The keywords extends and implements are used to indicate that an apex class is extending an existing class and that an apex class is implementing an interface, respectively.

Salesforce Apex does not support multiple inheritance; an apex class can only extend one other apex class, but it can implement multiple interfaces. Salesforce Apex does not support multiple inheritance.

Apex classes can contain user-defined constructors, and if no user-defined constructors are available, a default function Object() { [native code] } is used in their place. When a new instance of a class is created, the code contained in its function Object() { [native code] } is executed.

When creating an instance of an apex class, the new keyword is used to do so. The syntax for creating an instance of an apex class is shown in the following section.

obj = new myApexClass(); myApexClass obj = new myApexClass();

Apex Trigger is a term that refers to a trigger that occurs in an Apex object.

Triggers allow you to run custom apex code before and after a DML operation is performed in Oracle Database.

Several types of triggers are supported by Apex, including:

Triggers that occur before a record is saved to the database are used to validate and update the value of a field’s value.

Once committed to the database, these triggers are used to access fields (record ID and LastModifiedDate field) that have been set by the system after a record has been committed. The value of these fields can be used to modify the contents of other records. Records that are created as a result of triggers are read-only.

It is recommended that you avoid writing large triggers. A bulky trigger is capable of processing both a single record and multiple records at the same time.

In this case, TriggerName is the name of the trigger, ObjectName is the name of the object on which the trigger is to be written, and trigger events is a comma-separated list of the events that the trigger will fire.

The following events are supported by the apex triggers: before insert, before update, before delete, after insert, after update, after delete, after undelete, after undelete

In an Apex trigger, static keywords are not permitted to be used. In an Apex trigger, you can use any of the keywords that are applicable to inner classes.

Every trigger has an implicit variable that is defined by the trigger and returns the run-time context. All of these variables are defined within the system. Class for triggering an event. Context variables are the names given to these variables. The context variable supported by the apex trigger is depicted in the screenshot below.

The following are the factors that are taken into account when creating the apex trigger:

Don’t pull the trigger on anything.

In DML operations, the terms new and trigger.old are used.

Trigger.

It is not possible to delete a new.

Trigger.new is a read-only variable.

Trigger.new can be used to change the values of fields on the same object only in the time period before the trigger is fired.

The considerations for specific actions in different trigger events are listed in the following screenshots.

Apex Batch Class is a class that allows you to create batches of data.

Salesforce’s batch class is used to process large numbers of records that would otherwise exceed the apex governor limits if processed in a traditional manner. The code is executed asynchronously by the Batch class.

The following are some of the benefits of batch class:

The batch class processes data in chunks, and if one of the chunks fails to process successfully, all of the chunks that did successfully process do not roll back.

Governor limits are applied to each chunk of data in a batch class, ensuring that code is executed within the governor execution limits for that chunk of data in the batch class.

Database. If an apex class wishes to be used as a batch class, it must implement the Batchable interface first. The batch class must implement three methods that are provided by the batch class.

The following are the three interfaces that Database provides: batchable interface, batchable interface, and batchable interface.

1.start():

When this method is called, it generates the scope of records or objects that will be handled by the interface method execute. It is only called once during the course of a batch’s execution. This method either returns a Database or does not return anything. An Iterable or a QueryLocator object can be used. The number of records returned by a SQL query executed against a database is known as the response count. QueryLocator object has a capacity of 50 million records, but when using an iterable, the total number of records that can be retrieved by the SQL query is only 50,000 records, according to the documentation. To generate complex scope for the batch class, iterable is used as the generator.

The following is the syntax of the start method:

(Database.QueryLocator | IterablesObject>) global (Database.QueryLocator | IterablesObject>) the start() method of Database.BatchableContextbc is used.

2.execute():

Each chunk of data is processed using this method, which is described in detail below. The execute method is invoked for each chunk of records in the collection. The default batch size for execution is 200 records, which is the maximum possible. The method Execute accepts two arguments:

A reference to the Database can be found here.

This object is a BatchableContext object.

A list of sObjects, such as ListsObject>, or a list of parameterized types are examples of list structures. The syntax of the execute method is as follows:

execute(Database.BatchableContext BC, listP>) is a global void function.

{}

3.finish():

During the course of the batch class’s execution, the finish method is invoked once. The finish method has the capability of performing post-processing operations. For example, sending the confirmation email is an example of this. When the entire batch has been processed, this method is invoked. The Finish method has the following syntax:

finish(Database.BatchableContext BC) is a global void function.

Database.BatchableContext is a type of database context.

Each of the Database’s methods is described here. The Batchable interface contains a reference to the Database interface. BatchableContext is a type of context object.

Tracking the progress of the batch job is accomplished using this object.

BatchableContext provides the following instance methods, which are listed below:

This method accepts two parameters: an instance of the batch class to be processed, and an Options parameter to specify the batch size; if no batch size is specified, the default batch size of 200 is used instead.

By default, the Batch class has no states. A new copy of an object is received each time the execute method is invoked, and all of the variables in the class are initialised at that time.

Database.

It is necessary to implement stateful in order to make a batch class stateful.

The instance variables in your batch class will retain their values if your batch class implemented the Database, stateful interface; however, the static variables will be reset between each transaction.

Summary:

In the context of programming, Apex is a strongly typed object-oriented programming language that compiles and runs on the Force.com platform.

Because the Apex programming language does not care about case, it is a very flexible language.

In Apex, there are two types of flow of actions: 1) Developer action and 2) User action. 2) The action of the end-user

Apex is a tool that allows you to develop web services that integrate Salesforce with third-party software.

The following datatypes are supported by apex: 1).Primitive 2) Collections of items 3) sObject, Enums, and Constants 4) Groups of people, 5) Objects and Interfaces are important.

Apex provides specified support for the following types of databases: public, private, protected, and global.

The keywords that are used in Apex are: 1) with sharing, 2) without sharing, and 3) without sharing. 3) Static, 4) End result 5)Return, 6)Null, 7) Virtual, or virtualized 8) A brief summary

A string is a collection of characters with no restriction on the number of characters it can contain.

Apex governor limits are the limits enforced by the apex runtime engine to ensure that any runway apex code and processes do not exceed the limits set by the runtime engine.

It is possible to execute code before the property value is accessed or changed by using the getter and setter methods.

Creating apex classes in Salesforce can be done in three different ways: 1)The Developer’s Console (also known as the Developer’s Toolkit). 2)Force.com IDE, as well as 3) The detail page for an Apex class.

Triggers allow you to run custom apex code before and after a DML operation is performed in Oracle Database.

Salesforce’s batch class is used to process large numbers of records that would otherwise exceed the apex governor limits if processed in a traditional manner.