The world’s most popular CRM platform, Salesforce, is built on Apex. Or better said, Apex is the proprietary programming language of Salesforce and accounts for almost the whole platform alone.
Apex allows Salesforce developers to customize and create out-of-the-box solutions. A Salesforce developer is an individual who excels in the development of standard and custom Salesforce solutions using Apex programming.
Apex allows developers to execute process Flow and transaction control statements while witnessing API calls.
In addition, it enables Salesforce customers to add custom functionalities to their reliable applications.
This article will look into Apex and the perfect guide to becoming an Apex developer.
Apex is an object-oriented programming language and a proprietary language developed by Salesforce. It is a strongly-typed language. Moreover, it is effortless for strongly-typed languages to predict the nature of the behavior of the written code.
It enables the Salesforce developer to add custom business logic to several events, including button on-clicks, current and related record updates, and triggering visual Force and Lightning pages.
As Apex is the rich language of Salesforce, it is automatically upgraded with every new release or update of the Salesforce platform.
It is popularly known as the child of Java and has Java-like syntax. It uses simple programming syntax for loops, conditions, block statements, notation, etc. If anyone is accustomed to Java, learning Apex is simple.
As we’ve mentioned, Apex is a strongly-typed language. That means it requires you to define the data type of every new variable and follow the language performance restrictions.
Apex is integrated with the Salesforce database. Hence, it can access and move objects and records without needing to connect explicitly with the database. You can perform DML operations like “Insert,” “Delete,” and “Update.”
Moreover, it allows you to process multiple records keeping in mind governor limits.
Apex supports SOQL (Salesforce Object Query Language) and SOSL (Salesforce Object Search Language) to handle queries and fetch certain records.
A case-insensitive language allows developers to slack off with the capitalization of names. Case-insensitive languages treat ‘integer’ and ‘Integer’ the same, for example.
A multi-tenant environment is where multiple people share the same platform or application with the same database architecture trade-offs.
Testing Apex classes and triggers becomes accessible in the in-built environment for running test cases. You can simply create a test class, run a test, and see the complete code coverage for your class. The indicator shows the lines that have been covered.
Salesforce is a combination of point-and-click automation tools and programming with Apex. Although you can do anything with Apex, using it at every chance is not advisable. If there are tasks that are easily performed with tools like Flow and Process Builders, it is better to use them instead.
Apex can customize the standard Salesforce scalable applications, and with this wide range of functionalities and rich features, it is crucial to know when to use Apex.
Let’s take a look at some essential requirements and common scenarios where choosing Apex is a must:
When you have to build some complex logic that isn’t achievable with Workflow Rules, Process Builders, or Flow.
Salesforce offers multiple environments to its users. These environments support Apex product development, but there are some things that you need to keep in mind while working with Apex.
Developing Apex code in production can disrupt the database user experience or even break some functionality.
Whenever a developer creates and saves an Apex code on the platform, the Salesforce application server performs a few steps. It first compiles the Apex code into instructions understood by the Apex runtime. It then interprets the code and saves the instructions in the form of the compiled Apex.
When an end-user performs some Apex invoking action or triggers Apex execution from a button, the application server gets those compiled instructions sourced from the platform metadata. It then sends those instructions through Apex-runtime, which then performs the compilation.
However, the end-user doesn’t observe any difference in the execution time as it happens in the same runtime as a standard action.
Now that you know Apex’s basic definition, advanced features, and use cases, it’s time to get started with it. This section revolves around the entire development process for Apex. The process consists of four steps:
As we’ve already discussed, you can’t code Apex in a production environment. You need a developer organization or a sandbox with basic knowledge.
To create a sandbox organization, you need to:
Now you have a sandbox to develop and test Apex code. But first, you have to learn Apex, the basic syntax, triggers, integrations, asynchronous programming tools like Apex, etc. Apex is a very vast language with a wide range of use cases.
The first step of learning Apex is understanding its data types, operators, constructors, etc.
Now, let’s understand the development environment to create, test, and debug Apex classes.
There are several environments to carry on with Salesforce Apex development. However, there are two most widely used developer field environments. These are the Developer Console and VS (Visual Studio) Code with installed Salesforce CLI extensions (a powerful command line interface that simplifies development and builds automation).
The Developer Console is an IDE (Integrated Development Environment) hosted by Salesforce. It enables you to write, debug, and test Salesforce apps in your organization.
It acts as a one-stop solution for all your Salesforce development needs. For example, generating debug logs, browsing packages, and identifying and resolving errors.
Similarly, you can also use VS Code to develop Salesforce applications. The VS Code is a free code editor that supports developing and debugging modern web, cloud, and customer applications. Microsoft has developed VS Code with advanced features like syntax highlighting, intelligent code completion, snippets, embedding version control, etc.
Let’s try writing a simple Apex class in the Developer Console:
Log into your sandbox and click on the “Gear” icon.
public Account createNewAcc (String name) {
Account acc = new Account();
Acc. Name = name;
return acc;
}
You now have a simple Apex class that inserts a new account record every time it is ‘called.’ Your class, at last, should look like this:
public Class CreateAccount {
public Account createNewAcc (String name) {
Account acc = new Account();
Acc. Name = name;
return acc;
}
}
The class name is “CreateAccount,” and the method is “createNewAcc.” It takes one parameter, a string assigned to the variable name. The “createNewAcc” method takes the account name and creates a new account record with the given name.
The more you learn and practice Apex, the better you’ll understand its use cases and capabilities.
Moreover, learning Apex is incomplete without triggers, SOQL, SOSL, and asynchronous Apex.
An Apex trigger is a stored Apex procedure that executes whenever a change is introduced to Salesforce records. The changes include record creation, updates, deletes, upserts, undeletes, and merges. For example, you can have a trigger:
There are two types of triggers, and they are invoked in two cases – before and after the record changes are committed to the database. Understanding when to use ‘before’ or ‘after’ as a trigger is fundamental as it can be tricky sometimes.
An Apex trigger looks like this:
trigger TriggerName on ObjectName (trigger_events){
// code-block
}
Trigger events specify the case when the trigger is supposed to fire. There are seven trigger events in Salesforce:
Here are two examples of a trigger:
This first trigger fires before a new account record is inserted into the database and prints the given message in the log:
Trigger firstTrigger on Account(before insert) {
System.debug(‘I am before insert.’);
}
This second trigger fires after a new account record is inserted into the database and prints the given message in the log:
Trigger secondTrigger on Account(after insert) {
System.debug(‘I am after insert.’);
}
Trigger context variables enable the developers to access the runtime contexts of triggers. Salesforce contains these variables in the “System.Trigger” class. Here is a list of trigger context variables:
Some points to consider while working with context variables:
Bulkifying triggers are considered a best practice as it binds the triggers within the governor limits, consuming fewer server resources. Trigger bulkification refers to writing Apex triggers in a bulk pattern.
Salesforce lets you play around with organization data and its integrated database using Apex. Moreover, most of your work in Apex is related to sObjects and their records. Hence, learning SOQL, SOSL, and DML operations with Apex becomes important.
SOQL is a case-insensitive query language that retrieves Salesforce data from the database. SOQL should be used when you know the object where the data resides.
Use SOQL when you want to:
This is what a typical SOQL query looks like:
SELECT list_of_fields [subquery]
FROM object_name
[WHERE condition_expression]
[GROUP BY list_of_fields]
[HAVING condition_expression]
[ORDER BY list_of_fields {ASC|DESC} [NULLS {FIRST|LAST}] ]
[LIMIT count_of_rows_to_return]
[OFFSET count_of_rows_to_ignore]
An example would be:
Select name from account // standard object
Select name, Student_name from student__c // custom object
Select name from student__c where course__c = ‘Salesforce’; // where clause
SOQL is similar to SQL. You use SQL to retrieve data from database tables. While in SOQL, you query data from Salesforce objects.
However, SOQL has its features and criteria:
Salesforce has done a fantastic job introducing Apex variable binding. This enables you to use Apex variables in your SOQL query and filter records against it. For example:
String strName = 'flair.hr';
List positionList = [SELECT Name
FROM Company__c
WHERE Name =: strName];
Similar to SQL, SOQL supports aggregate functions like “Sum(),” “Max(),” “Min(),’” ”Avg(),” etc. Aggregate functions perform calculative operations on a set of values and return a single value. These are often used by the ‘group by’ clause and ignore null values retrieved in the query.
Dynamic SOQL queries are the queries formed at Apex runtime. These queries are generally in the form of SOQL strings and are used to generate dynamic queries that depend on the user’s input.
You can use “Database.query()” to work with dynamic SOQL:
Public static void main(String str)
{
String s1 = ‘select name from’ + str;
List<sObject> sList = Database.query(s1);
for(sObject s: sList)
{
System.debug(s);
}
}
SOSL is an optimized way of searching and querying records in Salesforce. Unlike SOQL, you don’t need to know the object or field where the data resides.
A SOSL query returns a list of sObjects as it can be performed on multiple objects simultaneously.
You can use SOSL when you want to:
Unlike SOQL and SQL, the SOSL query starts with the ‘find’ keyword. SOSL also supports wildcards that SOQL does not support. A wildcard is a character like an asterisk used to represent characters while searching the data. An example is:
List<List<sObject>> searchList = [FIND 'SFDC' IN ALL FIELDS
RETURNING Account(Name),
Contact(FirstName,LastName)];
Methods for asynchronous Apex are used to execute processes later in time. They run the tasks in the background without having the user wait for the execution. These processes are generally used for callouts beyond governor limits or with an external system.
These processes benefit the users as they are efficient, scalable, and have a higher execution limit. There are four different ways to implement Asynchronous Apex:
Asynchronous Apex methods are used to perform complex business needs that generally surpass the defined governor limits of Salesforce.
Salesforce offers an excellent testing feature for getting coverage for your Apex code. Apex testing is a process that involves creating classes with data and running them in Salesforce to test your code behavior and coverage.
Ideally, you should have a minimum of 75% test coverage of your Apex class. Any class with less than 75% coverage shouldn’t be deployed to production.
Apex testing requires you to test the following measurements:
The Apex test class methods are referred to as unit tests and are used to test whether a particular code block works as expected. These methods don’t take any argument or commit changes to the database.
Unit test methods are flagged using the ‘testMethod’ keyword or ‘isTest’ annotation at the beginning of the method definition. Also, test methods are only to be defined within test classes. Test classes are annotated with the ‘isTest’ keyword tool.
Ideally, each test method should have a different scenario that tests different behaviors of your Apex code. Let’s understand it better with an example:
@isTest
Private class myClass {
Static void testMethod myTest {
// code block
}
}
@isTest
Private class myClass {
@isTest
static void myTest() {
// code block
}
}
Here is an example test class that contains two test methods:
@isTest
Private class MyTestClass {
// Methods for testing
@isTest static void test1() {
// Implement test code
}
@isTest static void test2() {
// Implement test code
}
}
There are two system-defined unit test methods:
Apex testing is an integral and unavoidable part of Salesforce Apex development. It is more than just test data, coverage, and a few annotations.
Apex comes with excellent debugging support. You can debug Apex code with the help of the Developer Console and debug logs. You can also incorporate standard exception statements or create custom exceptions. Apex also sends email notifications with unhandled exception details to the developer.
As we’ve already discussed, Apex code is written in lower environments, like developer organizations or sandboxes (not in production), because the development may disrupt other live functionalities of the production organization.
To deploy Apex to upper environments, you can use:
Apex allows Salesforce developers to code back-end databases and client-side interfaces to create business-required SaaS applications. It also comes with an API that developers use to access organization data, standard web interfaces, and a range of tools.
It is an easy-to-use, data-focused, and rigorous programming language that supports multi-tenant environment structures. Apex proves to be the strongest weapon of a Salesforce developer.
Sign up for our newsletter & receive fresh content about all things Salesforce.