Skip to main content

Apex Best Practices

Explore practical guides and implementation patterns for this topic.

Posts

Salesforce Basics

Salesforce Async Apex Explained: The "Who Can Call Whom" Matrix

💬 In plain words: Navigating asynchronous Apex is all about knowing who is allowed to call whom. A Queueable can chain itself, and a Batch can start a Queueable . However, a @future method is a dead end—it cannot call another @future , and a Batch cannot call a @future . Memorizing this simple matrix eliminates an entire category of runtime crashes. Key Points at a Glance The Future is a Dead End: You cannot call a @future method from any other async context (Batch, Queueable, or another Future). Queueable is the Swiss Army Knife: You can enqueue a Queueable from a Trigger, a Batch execute() or finish() , and even chain it to another Queueable. Batch Chaining: You can legally chain a new Batch job, but only from the finish() method of the current Batch. Callout Rule: Callouts require the correct marker ( callout=true or Database.AllowsCallouts ) and can never occur after a DML operation in the same transaction. 📌 Real...
Read article
Salesforce Basics

Master Salesforce Governor Limits: SOQL, CPU Timeouts, and Apex Best Practices

💬 In plain words: Governor limits are like the referee in a shared stadium. Every time you run a transaction, Salesforce gives you a strict budget: a set number of database queries, DML statements, CPU time, and memory. This ensures no single tenant can hog the servers and crash the platform. You cannot fight limits; you must design for them by bulkifying your code, caching data, and moving heavy lifting to asynchronous processes. 📌 Example: The Scaling Problem Imagine a simple "Sync All Contacts" button. It worked perfectly for small boutique clients with a few hundred contacts. But when a bank with 80,000 contacts clicked it, the system threw an error: Too many query rows: 50001 . Governor limits didn't fail the developer—they acted as an alarm, signaling that this massive workload belongs in Batch Apex, not a real-time button click. 🎬 Real-Life Example: The Loop That Cost 101 Queries You write a trigger to enrich a Del...
Read article
Salesforce Basics

Salesforce Trigger Frameworks: Bulkification & Reentrancy Explained

⚡ 1-Minute Summary: Governor limits act as a transaction budget shared across your code, flows, and packages. Strictly enforce one trigger per object . Keep logic out of the trigger itself and build a bypass switch on day one. Use Queueable as your default asynchronous tool. Avoid writing new @future methods. Module Map: Programmatic Logic & Asynchronous Execution Trigger frameworks (bulkification, reentrancy) Synchronous vs. Asynchronous execution @future / Batch / Queueable / Scheduled Apex Governor limits (the platform's fairness budget) Exception handling & logging Platform Cache Quick Concept: Queues vs. Public Groups Q: What is the core difference between queues and public groups? A: Think of it as ownership versus audience . Queues own records. Unassigned work (like cases, leads, or custom objects) sits in a queue until a member claims it. Public Groups ow...
Read article
Apex Best Practices Apex Triggers Data Integrity Date Overlap Developer Guide Salesforce

How to Prevent Overlapping Date Ranges in Salesforce with Apex

In plain words: An overlapping date trigger acts as a bouncer for your database. It checks the calendar before a new record is saved to ensure you don't double-book a room, assign conflicting tax rates, or schedule overlapping employee shifts. If a conflict exists, it blocks the save and shows the user an error message. Maintaining pristine data quality in Salesforce often requires business rules that go beyond standard matching rules. When dealing with time-sensitive records—like subscription tiers, tax rates, or resource bookings—you must guarantee that no two records for the same category overlap in time. Because standard duplicate rules only look for exact matches, you need a bulkified before insert, before update Apex trigger to enforce this logic mathematically. 📌 Key Points Standard Salesforce duplicate rules cannot prevent partial date overlaps; you must use an Apex Trigger. Always run the trigger in the before context so yo...
Read article
Topic Apex & Dev
Apex & Dev

How to Prevent & Handle Apex Null Pointer Exceptions: Safe Navigation & Best Practices

In plain words: A Null Pointer Exception (NPE) happens when your code tries to open an empty box. If a variable or object points to null (nothing) and you attempt to read its fields, call its methods, or get its list items, Apex crashes because there is no data in memory to work with. In Salesforce development, the System.NullPointerException is one of the most frequent runtime runtime errors. Because Apex is strongly typed but initializes unassigned object references to null , any attempt to traverse unpopulated relationships, empty map lookups, or unassigned variables will throw an unhandled exception. Writing defensive, null-safe Apex keeps your applications stable and prevents unexpected transaction rollbacks. 1. Common Causes of Null Pointer Exceptions in Apex Most NPEs stem from missing runtime assumptions about how data is populated in memory: Uninitialized Variables & Collections: Declaring a list or custom object reference without inst...
Read article
Topic Apex Best Practices Apex Debugger Debug Logs Developer Console Salesforce Apex Troubleshooting VS Code Salesforce
Apex Best Practices Apex Debugger Debug Logs Developer Console Salesforce Apex Troubleshooting VS Code Salesforce

Salesforce Apex Debugging: Interactive Debugger, Breakpoints, & Log Inspection

In plain words: Debugging in Salesforce means pausing your running Apex code at specific lines (breakpoints) or reading execution history (debug logs) to inspect variables, find logic errors, and fix bugs without guessing. Diagnosing unexpected errors, null pointer exceptions, and governor limit spikes in Apex requires structured troubleshooting tools. Salesforce equips developers with both interactive debugging (stepping through code in real time) and historical log analysis (tracing execution events after runtime). Understanding how to configure these tools speeds up development and improves software quality. 1. Understanding Interactive Debugging vs. Debug Logs Salesforce provides two primary approaches to investigate Apex execution: Apex Debugger (Interactive): Allows you to pause live execution in sandbox or scratch org environments, step through lines of code, inspect in-memory call stacks, and evaluate variable values dynamically. Apex ...
Read article
Topic Apex Best Practices Error Handling Governor Limits Org Maintenance Salesforce Architecture Salesforce Development Unit Testing
Apex Best Practices Error Handling Governor Limits Org Maintenance Salesforce Architecture Salesforce Development Unit Testing

How to Avoid Errors in Salesforce: 6 Essential Best Practices for Developers & Admins

In plain words: Avoiding errors in Salesforce comes down to writing bulkified code that respects Governor Limits, testing with realistic data volumes, logging failures systematically, and enforcing strict data security rules across your org. Salesforce is a multi-tenant cloud platform, meaning every transaction shares memory, CPU time, and database resources with other processes. When custom automation, Apex triggers, or integrations aren't built defensively, teams run into unhandled exceptions, locking issues, and broken user workflows. Following disciplined architecture principles keeps your org healthy and error-free. 1. Adopt a Bulkified Testing Strategy Unit testing in Salesforce isn't just about reaching the 75% deployment threshold—it's about validating how your code behaves under peak transaction loads. A robust testing approach validates positive paths, negative edge cases, and 200-record batch triggers. Test for 200 Records: Nev...
Read article
Topic Apex Best Practices Custom Exceptions Error Logging Exception Handling Salesforce Apex Salesforce Development Try-Catch
Apex Best Practices Custom Exceptions Error Logging Exception Handling Salesforce Apex Salesforce Development Try-Catch

Apex Exception Handling: Complete Guide to Try-Catch, Custom Exceptions, & Best Practices

In plain words: Think of an exception as a surprise roadblock during code execution. Exception handling is your detour plan—using try-catch blocks to catch unexpected errors, log what went wrong, and keep your application running without crashing the user interface. In Salesforce development, writing defensive Apex code means planning for real-world failures: failed validation rules, missing records, locked database rows, and network timeouts. Implementing structured exception handling ensures that unexpected errors fail gracefully, preserve data integrity, and provide actionable feedback to users and developers. 1. Understanding Built-In Apex Exception Types Salesforce provides specific built-in exception classes derived from the base System.Exception class. Catching specific exceptions rather than generic ones helps you write targeted recovery logic: DmlException : Thrown when a database record insert, update, or delete violates validation rules,...
Read article
Topic Apex & Dev
Apex & Dev

Top Salesforce Apex Debugging Techniques: Logs, Breakpoints, & Best Practices

In plain words: Debugging Apex is like inspecting the black box of an airplane. Instead of guessing why a process failed, you can configure targeted debug logs, step through execution with the Apex Replay Debugger, set memory checkpoints, and filter noise to pinpoint bugs in seconds. Finding and fixing bugs in Salesforce requires a structured diagnostic approach. Because Apex runs in a multi-tenant cloud environment with strict governor limits, developers cannot simply pause production transactions at will. Mastering platform debugging tools—including Trace Flags, granular logging levels, Anonymous Apex, and interactive replay tools—dramatically reduces troubleshooting time. 1. Configuring Targeted Debug Logs & Trace Flags Debug logs track database operations, governor limit allocations, workflow rules, and custom Apex execution. Rather than capturing everything and hitting file size caps, configure targeted Trace Flags to collect only what you need. ...
Read article