Apex Development 101: The Basics of Apex

An Introduction to Apex

According to the Apex Developer Guide, Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the Salesforce Platform server, in conjunction with calls to the API.

Apex is very similar to Java, such as variable declaration, expressions, conditions, loop syntax and array notation. It supports data manipulation statements such as insert, update, and delete operations. It also has a built-in support for key Salesforce features, including inline Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) queries that return lists of sObject records, looping that allows for bulk processing of multiple records at a time, locking syntax that prevents record update conflicts, and custom public API calls built from stored Apex methods.

Why Apex?


Apex is a powerful option for customization. However, Salesforce also provides powerful declarative tools such as Flow Builder, Agent Builder and Approval Process. The guiding principle of Salesforce customizations is to use declarative solutions first before considering programmatic approach - which means that building a solution via code should only be considered when all means of declarative customizations cannot meet the requirements.

The following are some scenarios to consider on when we should use Apex:

  • Create web services for complex integration.
  • Create email services.
  • Perform complex validation that spans multiple objects.
  • Create complex business processes that aren’t supported by Flow Builder.
  • Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object).
  • Attach custom logic to another operation, such as saving a record, so that it occurs whenever the operation is executed, regardless of whether it originates in the user interface, a Visualforce page, or from SOAP API.

Sign Up for a Developer Org

For someone who's just starting with learning Apex, I suggest that you sign-up for your own Developer Org on this link. This provides access to many of the features available, including the Developer Console where you can write, test, and debug your code directly within Salesforce. Although the Developer Console is a lightweight, built-in tool that’s ideal for beginners, you can also explore more advanced development environments like Visual Studio Code as you progress.

The Developer Console

The Developer Console is a built-in IDE (Integrated Development Environment) within Salesforce, where developers can complete most of the essential coding tasks. It functions similarly to Java IDEs like Eclipse or IntelliJ. Although there are other Development Environment options where you can write Apex code such as Visual Studio Code, the Developer Console is a powerful section that provides the following abilities.

  • Add code on the source code editor, in addition to creating Apex classes.
  • Save Apex class or trigger which could mean that the code is compiling.
  • View debug logs and inspect the logs for locating performance bottlenecks.
  • Query data using SOQL on the Query Editor
  • Execute all or specific test classes and view test results

To open the Developer Console:

  • From Lightning Experience: Click the gear icon on the top right, then click Developer Console
  • From Salesforce Classic: Click Your Name, then Developer Console


Data Types

Before declaring variables in Apex, it must have a data type. The following are the common data types in Apex:

  • A primitive data type, such as an Integer, Double, Long, Decimal, Date, Time, Datetime, String, ID, or Boolean.
  • An sObject, which is either a generic sObject or a specific sObject (e.g. Account, Contact, MyCustomObject__c) NOTE: sObject stands for Salesforce Object.
  • A collection, including:
    • A list (or array) of primitives, sObjects, user defined objects, objects created from Apex classes, or collections
    • A set of primitives
    • A map from a primitive to a primitive, sObject, or collection
  • Objects created from Apex classes

When to Use Lists, Maps, and Sets in Apex

  • List: Use a list when you need an ordered collection of items. Lists are great for handling multiple records of the same type (e.g., a list of Account objects) and preserving the order of those records. Lists allow you to store and process data in bulk, making them essential when working with records retrieved from a SOQL query.

  • Set: Use a set when you need a unique collection of items without duplicates, and the order doesn’t matter. Sets are helpful for filtering out duplicate values or performing bulk operations, such as adding a unique set of IDs to ensure you’re working with distinct records.

  • Map: A map is a collection of key-value pairs, ideal when you need to associate each item with a unique key (e.g., ID to Account). Maps are highly efficient for lookups and retrievals, making them useful when you need to access data by a unique identifier, like matching an account name to its record ID.


Variables in Apex

Variable declaration in Apex is the same as Java. Multiple variables can be declared and initialized in a single statement, as shown below:

Integer count = 0;
String firstString, secondString, thirdString;
List<Account> accountList = new List<Account>();
Map<ID, String> idToStringMap;


Conditional Statements in Apex


The conditional statements in Apex are similar to those in Java. The if-else statement is used to control the flow of execution in Apex and can take in many forms such as (1) the if statement, (2) the if-else statement, or (3) the if-else-if statement.

if ([Boolean_condition]) {
    // Statement 1
} else {
    // Statement 2
}

Here is an example of using an if-else-if statement in Apex. This code assigns an assessment based on the score value: “Failed” if the score is below 50, “Needs Improvement” if it’s between 50 and 70, and “Passed” for scores above 70.

String assessment = '';
if (score < 50) {
   assessment = 'Failed';
} else if (score >= 50 && score <= 70) {
   assessment = 'Needs Improvement';
} else {
   assessment = 'Passed';
}

Loops in Apex

Apex supports five types of procedural loops. These types of procedural loops are supported:
  • do {statement} while (Boolean_condition);
  • while (Boolean_condition) statement;
  • for (initialization; Boolean_exit_condition; increment) statement;
  • for (variable : array_or_set) statement;
  • for (variable : [inline_soql_query]) statement;

The for loop is the most used looping structure in Apex. When looping records on a custom object, we can use the collection containing the records, or we can query the records directly. The following are examples:

Using for loop to iterate collection

List<Account> accountList = [SELECT Id, Name FROM Account];
for (Account acc : accountList) {
   // process records here
}


Using SOQL for loop

for (Account acc : [SELECT Id, Name FROM Account]) {
   // process records here
}

All loops allow for loop control structures:
  • break; - exits the entire loop
  • continue; - skips to the next iteration of the loop

Conclusion

Practicing with Apex is the best way to become comfortable with Salesforce development. Use a Developer Org to experiment with code examples, and refer to the resources below for further learning.

Remember, while Apex is a powerful programming language, Salesforce is designed with robust declarative options. Aim to use "clicks not code" whenever possible - this approach not only simplifies maintenance but also aligns with Salesforce's best practices.

Resources

Apex Developer Guide 

Trailhead: Apex Basics & Database

Trailhead: Quick Start: Apex





Post a Comment

0 Comments