Skip to main content
Base Platform  /  Code Snippet Archive

Code Snippet & Reference Library

Battle-tested, copy-pasteable snippets across PHP, Python, JavaScript, VB.NET, SQL and Bash — compiled from real SaaS engineering sessions.

469
Snippets Indexed
2
PHP
0
JavaScript
7
Python
✕ Clear

Showing 2 snippets · Apex

Clear filters
SNP-2025-0282 Apex Apex programming code examples 2025-07-06

How Can You Effectively Leverage Apex for Complex Business Logic in Salesforce?

THE PROBLEM

Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the Salesforce platform's server. It is crucial in customizing Salesforce applications and is particularly powerful when it comes to implementing complex business logic. This post delves into the ways Apex can be utilized effectively for developing sophisticated applications, covering a range of topics from core concepts to advanced techniques and common pitfalls. Understanding how to harness Apex's capabilities can significantly enhance your Salesforce development skills and the functionality of your applications.

Apex was introduced in 2007 as part of the Salesforce platform. It allows developers to write code that performs operations on the Salesforce database, execute business logic, and integrate with external systems. Apex is tightly integrated into the Salesforce ecosystem, enabling developers to build custom applications and functionalities that can scale with business needs. The language is syntactically similar to Java, which makes it easier for Java developers to pick up quickly. However, Apex has unique features tailored to the Salesforce environment.

To effectively leverage Apex for complex business logic, it is essential to understand its core technical concepts, including:

  • Classes and Triggers: Apex uses classes to define the structure and functionality of your code. Triggers are special types of classes that execute before or after data manipulation language (DML) operations on Salesforce objects.
  • Governor Limits: Salesforce imposes limits on the resources that can be consumed by Apex code to ensure efficient sharing of its multi-tenant environment. Understanding these limits is critical for writing efficient code.
  • SOQL and SOSL: Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) are used to query Salesforce data. Mastering these query languages is essential for data manipulation in Apex.

When implementing complex business logic, consider the following key strategies:

1. Using Triggers for Automation

Triggers are a powerful way to automate business processes in Salesforce. You can use triggers to run Apex code before or after records are inserted, updated, or deleted. Here's an example of a simple trigger that updates a field on the related Account when a Contact is created:

trigger UpdateAccountOnContactCreate on Contact (after insert) {
    List accountsToUpdate = new List();
    
    for (Contact contact : Trigger.new) {
        if (contact.AccountId != null) {
            Account acc = new Account(Id = contact.AccountId);
            acc.Last_Contact_Date__c = Date.today();
            accountsToUpdate.add(acc);
        }
    }
    
    update accountsToUpdate;
}
💡 Tip: Use bulk processing in triggers to handle large datasets efficiently and avoid hitting governor limits.

2. Creating Custom Apex Classes

Custom classes allow you to encapsulate business logic and promote code reuse. For instance, you can create a class that handles the logic for calculating discounts based on various criteria:

public class DiscountCalculator {
    public static Decimal calculateDiscount(Decimal originalPrice, Integer discountPercentage) {
        if (discountPercentage < 0 || discountPercentage > 100) {
            throw new IllegalArgumentException('Discount percentage must be between 0 and 100');
        }
        return originalPrice - (originalPrice * discountPercentage / 100);
    }
}

3. Asynchronous Apex for Long-running Processes

For processes that may take a long time to execute, such as batch processing or callouts to external systems, using asynchronous Apex is advisable. This includes using Batch Apex, Queueable Apex, and Future methods. Here's a simple example of a Queueable Apex class:

public class AsyncProcessing implements Queueable {
    public void execute(QueueableContext context) {
        // Long-running process here
    }
}
⚠️ Warning: Always handle exceptions in your asynchronous processes to avoid failures that can be hard to trace.

When working with Apex, adhering to best practices can greatly enhance code maintainability and performance:

1. Write Test Classes

Salesforce requires at least 75% test coverage for deployments. Writing robust test classes not only helps you meet this requirement but also ensures your code behaves as expected. Here's an example of a test class:

@isTest
private class DiscountCalculatorTest {
    @isTest
    static void testCalculateDiscount() {
        Decimal result = DiscountCalculator.calculateDiscount(100, 20);
        System.assertEquals(80, result);
    }
}

2. Use Custom Settings and Custom Metadata Types

Instead of hardcoding values, leverage Custom Settings and Custom Metadata Types for configuration. This enhances flexibility and allows you to change values without modifying the code.

Security is paramount in Apex development. Here are some best practices to consider:

1. Enforcing Field-Level Security

Always check user permissions and field-level security when accessing data in Apex. This helps prevent unauthorized access to sensitive information:

if (Schema.sObjectType.Account.fields.Industry.isAccessible()) {
    // Access industry field
}

2. Preventing SOQL Injection

Use bind variables in your SOQL queries to prevent SOQL injection attacks:

String searchTerm = 'Acme';
List accounts = [SELECT Id, Name FROM Account WHERE Name LIKE :searchTerm];

1. What is the difference between Apex and Visualforce?

Apex is a programming language used to execute logic on the Salesforce server, while Visualforce is a framework for building user interfaces in Salesforce applications. Apex can be used in conjunction with Visualforce pages to handle server-side processing.

2. How do I debug Apex code?

You can debug Apex code using the Developer Console, debug logs, and System.debug statements. Set the appropriate log levels to capture the necessary details during execution.

3. Can Apex call external APIs?

Yes, Apex can call external APIs using HTTP callouts. You can use the Http class to send requests to external services and handle responses.

4. What are the best tools for Apex development?

Popular tools include Salesforce Developer Console, Visual Studio Code with Salesforce Extensions, and the Salesforce CLI. These tools provide features for code editing, debugging, and deployment.

5. How can I improve the performance of my Apex code?

To improve performance, optimize SOQL queries, minimize DML operations, use bulk processing, and avoid unnecessary loops. Follow best practices for efficient coding to reduce resource consumption.

In conclusion, leveraging Apex for complex business logic in Salesforce requires a solid understanding of its features, common pitfalls, and best practices. By implementing triggers, custom classes, and asynchronous processes, you can create robust applications that meet your business requirements. Always prioritize performance and security in your development process to ensure a seamless user experience. As Salesforce continues to evolve, staying updated with the latest features and improvements will further enhance your Apex development skills. Happy coding!

PRODUCTION-READY SNIPPET

Even seasoned developers can run into issues while working with Apex. Here are some common pitfalls and their solutions:

1. Exceeding Governor Limits

One of the most common issues in Apex development is hitting governor limits. Always keep an eye on the limits for CPU time, DML operations, and SOQL queries. To avoid this, optimize your code by:

  • Minimizing the number of SOQL queries.
  • Using collections to handle multiple records.
  • Using efficient algorithms for large datasets.

2. Inefficient Trigger Logic

Triggers can become inefficient if not designed properly. To mitigate this, follow best practices such as:

  • Implementing a trigger framework to manage logic.
  • Using the 'One Trigger Per Object' rule to keep trigger logic centralized.
PERFORMANCE BENCHMARK

Optimizing the performance of your Apex code can lead to significant improvements in execution speed and resource utilization:

1. Efficient Querying

When querying data, always use selective filters to reduce the amount of data processed. For example:

List accounts = [SELECT Id, Name FROM Account WHERE Industry = 'Technology' LIMIT 100];

2. Bulk Processing

Utilize bulk processing capabilities of Apex to handle large volumes of records. This involves using collections and bulk DML operations, which are more efficient than processing records one at a time.

Open Full Snippet Page ↗
SNP-2025-0210 Apex Apex programming code examples 2025-04-29

How Can You Leverage Apex for Enterprise-Level Salesforce Development?

THE PROBLEM

As organizations increasingly turn to Salesforce for their CRM solutions, the demand for skilled Apex developers has surged. Apex, a strongly typed, object-oriented programming language built specifically for the Salesforce platform, allows developers to execute flow and transaction control statements on the Salesforce server. This question of leveraging Apex for enterprise-level development is crucial, as it encompasses understanding the language's capabilities, best practices, and common pitfalls.

Apex was introduced in 2007 as part of Salesforce's platform to empower developers to build complex business logic directly within the Salesforce ecosystem. Unlike other programming languages, Apex is designed to run in a multi-tenant environment, meaning it must operate efficiently for all users of the Salesforce platform. Understanding its historical evolution helps in grasping its unique features and limitations.

Apex is tightly integrated with Salesforce's data model and provides several core features that distinguish it from other programming languages:

  • Object-Oriented: Apex supports object-oriented programming principles, including classes, interfaces, and inheritance.
  • Built-in Database Support: Apex has built-in support for Salesforce's database, allowing developers to perform SOQL and SOSL queries directly.
  • Asynchronous Processing: Apex supports asynchronous operations, such as Batch Apex, Queueable Apex, and Future methods, enabling developers to process large volumes of data or long-running tasks without blocking.
  • Governor Limits: Salesforce imposes governor limits on resources to ensure no single tenant monopolizes the platform's resources.
Tip: Familiarize yourself with Salesforce's governor limits to optimize your Apex code effectively. This will help prevent runtime exceptions due to exceeding limits.

To take your Apex skills to the next level, consider the following advanced techniques:

Batch Apex

Batch Apex allows you to process large data sets asynchronously. This is particularly useful when working with thousands of records.

global class AccountBatch implements Database.Batchable {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator('SELECT Id FROM Account');
    }
    global void execute(Database.BatchableContext BC, List scope) {
        // Process the records
    }
    global void finish(Database.BatchableContext BC) {
        // Post-processing logic
    }
}

Queueable Apex

Queueable Apex is a more flexible way to perform asynchronous operations compared to Future methods, allowing for complex job chaining.

public class MyQueueableJob implements Queueable {
    public void execute(QueueableContext context) {
        // Job logic
    }
}

Adhering to best practices can significantly improve the quality and maintainability of your Apex code:

  • Follow Naming Conventions: Use meaningful names for classes, methods, and variables.
  • Use Comments: Document your code with comments to explain complex logic.
  • Modularize Your Code: Break down large classes into smaller, reusable components.

Security should be a top priority when developing Apex code. Follow these practices:

  • Use with sharing: Classes should use the 'with sharing' keyword to enforce sharing rules.
  • Validate User Input: Always validate before processing any user inputs to avoid SOQL injection attacks.
  • Limit Data Exposure: Only query the fields necessary for your business logic.

When developing applications on Salesforce, you might wonder how Apex compares with other frameworks:

Framework Strengths Weaknesses
Apex Seamless Salesforce integration, built-in database support Governor limits, vendor lock-in
Java Robust and mature, extensive libraries Requires external systems for CRM
Node.js Asynchronous programming model, extensive community support Requires separate API integrations for Salesforce

1. What is the difference between Trigger.new and Trigger.old?

Trigger.new refers to the new version of the records being processed, while Trigger.old refers to the previous version of the records. This is crucial for understanding changes made during update operations.

2. How can I handle exceptions in Apex?

Use try-catch blocks to handle exceptions effectively. This allows you to manage errors gracefully instead of causing runtime failures.

try {
    // Code that may throw an exception
} catch (Exception e) {
    System.debug('Error: ' + e.getMessage());
}

3. What is the purpose of @future methods?

@future methods allow you to run processes asynchronously, which is useful for operations that do not require immediate feedback, such as sending emails or making callouts.

4. How can I improve the performance of my SOQL queries?

Utilize selective filters, leverage indexed fields, and avoid querying unnecessary fields to enhance the performance of your SOQL queries.

5. What are the key differences between Batch Apex and Queueable Apex?

Batch Apex can process large data volumes and is designed for bulk processing, while Queueable Apex is more flexible and allows for chaining jobs, which is easier for smaller tasks.

Apex is a powerful tool for enterprise-level Salesforce development, offering unique capabilities that can significantly enhance business processes. By understanding its core concepts, following best practices, and avoiding common pitfalls, developers can create robust applications that leverage the full power of Salesforce. As you dive deeper into Apex, remember to continuously refine your skills and stay updated on best practices and new features. The Salesforce ecosystem is constantly evolving, and so should your expertise in Apex.

PRODUCTION-READY SNIPPET

As with any programming language, Apex comes with its own set of common pitfalls:

Exceeding Governor Limits

One of the most frequent issues developers face is exceeding governor limits. To avoid this, follow these practices:

  • Use bulk processing to handle multiple records at once.
  • Avoid SOQL queries inside loops.
  • Utilize collections to store data temporarily.

Debugging Apex Code

Debugging can be challenging, especially in a multi-tenant environment. Use the following techniques:

  • Utilize System.debug() statements to log variable values.
  • Leverage the Developer Console for real-time monitoring.
  • Write unit tests to catch errors early.
Warning: Always write test classes for your Apex code. Salesforce requires a minimum of 75% code coverage on deployments.
REAL-WORLD USAGE EXAMPLE

To effectively leverage Apex in enterprise-level applications, developers must focus on practical implementation details:

Basic Apex Syntax

Apex syntax is similar to Java, making it easier for Java developers to transition. Here's a simple hello world example:

public class HelloWorld {
    public static void sayHello() {
        System.debug('Hello, World!');
    }
}

Creating a Trigger

Triggers are one of the most powerful features of Apex. They allow you to execute code before or after specific data manipulation language (DML) events on Salesforce objects.

trigger AccountTrigger on Account (before insert, before update) {
    for (Account acc : Trigger.new) {
        acc.Name = acc.Name + ' - updated';
    }
}
PERFORMANCE BENCHMARK

Optimizing performance in Apex is essential for scaling applications. Consider these techniques:

  • Use indexed fields in SOQL queries to improve lookup times.
  • Batch process DML operations to minimize transaction limits.
  • Cache results when appropriate to reduce redundant queries.
Open Full Snippet Page ↗