Getting Started with Salesforce Apex — Apex Part 2

Mohammad Usman
6 min readMar 12, 2024

--

Salesforce is one of the leading customer relationship management (CRM) platforms, widely used across various industries. One of its key strengths is its extensibility, allowing developers to build custom functionalities using Apex, a strongly typed, object-oriented programming language. Whether you’re new to Salesforce development or looking to enhance your skills, this guide will provide a comprehensive introduction to getting started with Apex.

Salesforce apex

Setting up Salesforce Developer Environment

Before diving into Apex development, it’s essential to set up your Salesforce developer environment. Salesforce offers a variety of tools and resources to facilitate this process:

1. Sign up for a Developer Edition account: Developer Edition accounts are free and provide access to a fully functional Salesforce environment for development purposes, click here to sign up free.

2. Install Salesforce Extensions for Visual Studio Code (VS Code): VS Code is a powerful code editor that integrates seamlessly with Salesforce development. Install the Salesforce Extensions to leverage features like code completion, syntax highlighting, and Salesforce-specific extensions. Click here to download the VS code.

3. Enable Dev Hub: Dev Hub is a set of Salesforce features that enable you to create and manage Salesforce environments, known as Salesforce DX (Developer Experience) orgs. Enable Dev Hub in your Developer Edition account to access these features.

4. Install Salesforce CLI: The Salesforce Command Line Interface (CLI) is a powerful tool for interacting with Salesforce orgs from the command line. Install it to perform various tasks such as creating scratch orgs, deploying metadata, and running Apex tests.

Introduction to Developer Console and Salesforce CLI

Once your development environment is set up, familiarize yourself with two key tools for Apex development: Developer Console and Salesforce CLI.

1. Developer Console:
Developer Console is a web-based integrated development environment (IDE) provided by Salesforce.
— It offers features like code editing, debugging, and performance analysis.
— Use the Developer Console to write, test, and debug Apex code directly within the Salesforce environment.

2. Salesforce CLI:
Salesforce CLI is a command-line interface that provides a more flexible and efficient way to interact with Salesforce orgs.
— It allows you to perform various development tasks, such as creating and managing orgs, deploying code, and running tests.
— Salesforce CLI is particularly useful for automating repetitive tasks and integrating with other development tools and processes.

Basic Apex Syntax and Structure

Now that you’re acquainted with the development environment and tools, let’s explore the basic syntax and structure of Apex:

1. Apex Classes:
— Apex code is organized into classes, which are similar to classes in object-oriented programming languages like Java and C#.
— A class in Apex encapsulates data and methods that operate on that data.
— Example:

public class MyClass {
public String greeting;

public MyClass() {
greeting = 'Hello, world!';
}

public void displayGreeting() {
System.debug(greeting);
}
}

2. Apex Variables and Data Types:
— Apex supports various data types, including primitive types (e.g., Integer, Boolean), collections (e.g., List, Set, Map), and custom types (e.g., custom objects).
— Variables must be declared with a specific data type before they can be used.
— Example:

 Integer count = 10;
Boolean isActive = true;
List<String> dataTypes = new List<String>{‘Alice’, ‘Bob’, ‘Charlie’};
System.debug(dataTypes); // result Alice, Bob, Charlie

3. Apex Methods:
— Methods in Apex are similar to functions in other programming languages.
— They encapsulate a set of actions or computations and can accept parameters and return values.
— Example:

public Integer addNumbers(Integer a, Integer b) {
return a + b;
}
System.debug(addNumbers(2, 5)); // result 7

4. Apex Control Structures:
— Apex supports standard control structures like if statements, loops, and switch statements for flow control.
— Example:

Integer score = 85;
if (score >= 90) {
System.debug('Excellent!');
} else if (score >= 70) {
System.debug('Good job!');
} else {
System.debug('Keep practicing!');
}

Anonymous code execution

Executing anonymous Apex code in Salesforce allows developers to quickly test code snippets or perform one-time operations without the need to create a separate Apex class or trigger. Here are the steps to execute anonymous code in Salesforce:

1. Access Developer Console or Salesforce CLI: You can choose to execute anonymous Apex code either through the Developer Console or Salesforce CLI. Both methods provide similar capabilities, so use whichever you’re more comfortable with.

2. Open Developer Console:
— Log in to your Salesforce Developer Edition or sandbox environment.
— Navigate to the Developer Console by clicking on your name → Developer Console.

3. Create New Anonymous Apex Window:
— In the Developer Console, go to the “Debug” menu.
— Select “Open Execute Anonymous Window.”

4. Write Your Apex Code:
— In the Execute Anonymous window, write your Apex code snippet. The code should be self-contained and not require any external dependencies.
— For example:

 // Example: Inserting a new Account record
Account acc = new Account(Name=’Test Account’);
insert acc;

5. Execute the Code:
— Once you’ve written your code snippet, click on the “Execute” button to run the code.
— Salesforce will compile and execute the Apex code snippet in a secure and isolated environment.

6. View Execution Results:
— After execution, the results will be displayed in the “Logs” tab at the bottom of the Developer Console.
— Review the debug logs for any errors, exceptions, or output generated by your code.

Alternatively, if you prefer using Salesforce CLI:

1. Open Terminal or Command Prompt:
— Launch your preferred terminal or command prompt.

2. Authenticate with Salesforce CLI:
— Authenticate with your Salesforce org using Salesforce CLI if you haven’t already done so.
— Run the command:

 sfdx force:auth:web:login -d -a <alias>

— Replace `<alias>` with a name for your org connection.

3. Create a Temporary Apex File:
— Create a new file with a `.apex` extension (e.g., `test.apex`) and write your Apex code snippet in this file.
— For example:

 // Example: Inserting a new Contact record
Contact con = new Contact(
FirstName=’John’,
LastName=’Doe’,
Email=’john.doe@example.com’
);
insert con;

4. Execute the Apex File:
— Run the following Salesforce CLI command to execute the Apex code in the temporary file:

 sfdx force:apex:execute -f <path/to/apex/file>

— Replace `<path/to/apex/file>` with the path to your temporary Apex file.

5. Review Execution Results:
— After execution, Salesforce CLI will display the execution results in the terminal.
— Check for any errors or output generated by your code.

By following these steps, you can easily execute anonymous Apex code in Salesforce using either the Developer Console or Salesforce CLI, enabling you to quickly test and validate your code snippets or perform one-time operations.

Resources for Further Learning

To further enhance your understanding of advanced Apex features and Salesforce development in general, here are some recommended resources:

- Salesforce Apex Developer Guide: The official Apex developer guide provides comprehensive documentation and examples for mastering Apex programming.
- Trailhead: Salesforce’s interactive learning platform offers a wide range of modules and trails on Apex development, asynchronous processing, integrations, and more.
- Salesforce Developer Blog: Stay updated with the latest news, tips, and best practices from Salesforce developers and experts through the official developer blog.
- Stack Exchange — Salesforce: Engage with the Salesforce community, ask questions, and share knowledge on Stack Exchange’s dedicated Salesforce platform.

Conclusion

In this guide, we’ve covered the fundamentals of getting started with Apex in Salesforce development. From setting up your developer environment to understanding basic Apex syntax and structure, you’re now equipped with the knowledge to begin your journey as a Salesforce developer. As you continue to explore Apex and build custom solutions on the Salesforce platform, remember to leverage resources like documentation, forums, and developer communities to enhance your skills and stay updated with best practices and new features. Happy coding!

--

--

Mohammad Usman

Trailblazer | Transforming Businesses through Salesforce Expertise | Salesforce Technical Architect, Consultant & Developer | Technical Lead