Skip to main content

Posts

Showing posts with the label APEX

Loops in Apex

There are 5 loop Types in Apex But not all of them are used Using while loops is considered a bad practice, because...it's easy to mess up From remaining 3 - for each is used 90% of the time But standard for loop is fundamental If you understand the standard loop, you understand all other types So, let's do it Definition: Loop is a block of code that runs a certain number of times Let's look at the example Let's say, I want to output 5 times (or 500) "Wow, I love Apex" to logs, but I am too lazy to write each line

Asynchronous Apex in Salesforce

๐Ÿš€ Asynchronous Apex in Salesforce Asynchronous Apex is used for long-running, resource-intensive, or bulk operations that can't run within the standard synchronous limits. Salesforce provides several async mechanisms to meet different needs. --- ๐Ÿ“Œ Why Use Async Apex? ✅ Handle large volumes of data ✅ Avoid governor limits ✅ Perform non-blocking tasks (e.g., callouts) ✅ Execute scheduled tasks --- 1️⃣ Batch Apex Used to process millions of records in manageable chunks asynchronously. Key Methods: start() – Returns a query locator or iterable execute() – Processes each batch finish() – Final logic (e.g., email notifications) Example: Batch Apex global class AccountBatch implements Database.Batchable<sObject> { global Database.QueryLocator start(Database.BatchableContext bc) { return Database.getQueryLocator('SELECT Id, Name FROM Account'); } global void execute(Database.BatchableContext bc, List<...

Triggers in Salesforce

⚙️ Writing Triggers in Apex Triggers are essential for automating logic in Salesforce. They run before or after DML operations on records and allow you to enforce business rules at the database level. --- ๐Ÿ• Before vs After Triggers Before Triggers : Used to modify record values before saving to the database. After Triggers : Used when you need the record's ID or want to perform operations on related records. Trigger Type Use Case before insert Set default values before saving after insert Log creation, send notifications before update Validate or modify updates after update Act on changes with old/new values before delete Prevent deletion with custom checks after delete Clean up related records after undelete Re-link relationships after restore --- ๐ŸŽฏ Trigger E...

Apex Best Practices

✅ Apex Best Practices: Separation of Concerns & Modular Coding Writing clean, scalable Apex code requires following key best practices such as Separation of Concerns (SoC) and Modular Coding . These help you build maintainable, testable, and reusable Salesforce applications. ๐Ÿ“Œ What is Separation of Concerns? Separation of Concerns means dividing code into distinct sections, each handling a specific responsibility. In Apex, this typically involves: ๐Ÿ” Keeping Triggers free of business logic ๐Ÿง  Moving logic to Handler and Helper classes ๐Ÿ”ง Using Utility classes for common logic --- ๐Ÿ“ Recommended Structure /triggers ContactTrigger.trigger /classes ContactTriggerHandler.cls ContactHelper.cls ValidationUtils.cls --- ๐Ÿงฉ Example: Good Modular Design 1️⃣ Trigger (Only Entry Point) ContactTrigger.trigger trigger ContactTrigger on Contact (before insert) { ContactTriggerHandler.handleBeforeInsert(Trigger.new); } Copy Code 2️⃣ Hand...

Apex Service Layer Design

๐Ÿงฑ Apex Service Layer Design: Helper & Handler Classes In Apex, the **Service Layer pattern** is used to organize logic in a modular and scalable way. It separates your **trigger logic**, **business logic**, and **utility logic** into focused components: Trigger → Handler Class : Controls the flow based on the context. Handler → Helper Class : Performs the actual business logic. ๐Ÿ“ Why Use Service Layer? ๐Ÿ”„ Makes code reusable and easier to test ๐Ÿงช Simplifies unit testing by separating concerns ⚙️ Prevents logic inside triggers directly (recommended best practice) --- ๐Ÿ“ Folder Structure (Conceptual) /triggers AccountTrigger.trigger /classes AccountTriggerHandler.cls AccountHelper.cls --- 1️⃣ Trigger File This is just a delegator, calling the handler class. AccountTrigger.trigger trigger AccountTrigger on Account (before insert, after update) { AccountTriggerHandler.handle(Trigger.isBefore, Trigger.isAfter); } Copy Code ...

Apex Trigger Development

๐Ÿ” Apex Trigger Development (Before & After Events) Triggers in Apex are used to perform custom actions before or after changes are made to Salesforce records (like insert, update, delete). They are event-driven and can be used for data validation, automation, or calling Apex logic. ๐Ÿ“Œ Trigger Syntax General Syntax trigger TriggerName on ObjectName (trigger_events) { // Trigger logic } Copy Code --- ⚙️ Before vs After Triggers Trigger Type When it Executes Use Case Before Before record is saved to DB Validation, setting default values After After record is saved to DB Create related records, send emails, access Record ID --- 1️⃣ Before Insert Example Set a default value before the record is saved. Trigger: Before Insert trigger ContactDefaultTitle on Contact (before insert) { for(Contact c : Trigger.new) { if(c.Title == null...

Collections: List, Set, Map

Apex Collections: List, Set, Map Apex provides three powerful types of collections to handle groups of data: List , Set , and Map . These collections help manage bulk records, loop through data, and perform DML operations efficiently. 1️⃣ List in Apex A List is an ordered collection of elements that allows duplicates. It's similar to an array in other languages. Example: List List fruits = new List (); fruits.add('Apple'); fruits.add('Banana'); fruits.add('Apple'); // Duplicate allowed System.debug(fruits); System.debug(fruits[0]); // Access by index Copy Code ๐Ÿ”ธ Common List Methods: add(value) get(index) size() contains(value) 2️⃣ Set in Apex A Set is an unordered collection that contains only unique elements. Example: Set Set countries = new Set (); countries.add('India'); countries.add('USA'); countries.add('India'); // Ignored (duplicate) System.debug(countries); System...

Static vs. Instance Context

In Apex, understanding the difference between static and instance context is crucial for designing efficient and maintainable code. ๐Ÿ”น What is Static Context? A static variable or method belongs to the class itself , not to any specific instance (object) of that class. You don’t need to create an object to use a static member. Example: Static Method & Variable public class Utils { public static Integer count = 0; public static void logMessage(String msg) { System.debug('Log: ' + msg); count++; } } Copy Code Usage: Utils.logMessage('Start process'); System.debug(Utils.count); // Output: 1 Copy Code ๐Ÿ”น What is Instance Context? An instance variable or method belongs to an object created from a class. You need to create an object to use instance members. Example: Instance Method & Variable public class Person { public String name; public Person(String name) { this....

Apex Classes, Methods, and Interfaces

Apex is an object-oriented programming language used in Salesforce. Understanding classes, methods, and interfaces is essential for writing reusable, scalable, and maintainable code. 1. Apex Class A class is a blueprint that defines variables (fields) and functions (methods). In Apex, all code must reside in a class. Syntax: public class ClassName { // Variables // Methods } Copy Code Example: public class Car { public String brand; // Constructor public Car(String carBrand) { brand = carBrand; } // Method public void displayBrand() { System.debug('Brand: ' + brand); } } Copy Code Usage: Car c = new Car('Tesla'); c.displayBrand(); // Output: Brand: Tesla Copy Code 2. Apex Method A m...

Apex Control Statements

Apex, Salesforce’s programming language, includes several control statements to control the flow of logic in your code. These include: if / else switch for loops while / do-while loops Let’s go through each with clear syntax, examples, and explanation. 1. if, else if, else Statement The if statement executes a block of code only if a specified condition is true. Syntax: if (condition) { // code if condition is true } else if (otherCondition) { // code if otherCondition is true } else { // code if none are true } Copy Code Example: Integer score = 75; if (score >= 90) { System.debug('Grade A'); } else if (score >= 75) { System.debug('Grade B'); } else { System.debug('Grade C'); } Copy Code Output: Grade B Copy C...

APEX ACCESS MODIFIERS - With Sharing • Without Sharing

 APEX ACCESS MODIFIERS - With Sharing • Without Sharing In Apex , access modifiers like with sharing and without sharing determine how a class enforces sharing rules (such as object-level and record-level security). These modifiers do not control visibility like public or private do — they control whether record-level access is respected. APEX SHARING MODIFIERS with sharing Enforces the current user's sharing rules . Only allows access to records that the user has permission to see. Recommended for most business logic to respect security. demo without sharing Ignores sharing rules (runs in system context ). Can access all records , regardless of user's access. Use with caution , typically for admin-level operations or utilities. Default Behavior (If Omitted) If neither with nor without sharing is specified: Default is "inherited" from the caller class if one exists. If the class is run from anonymous Apex or triggers , it r...

Apex Data Types

Apex supports various data types categorized into primitive types, collections, sObjects, and complex types. Below is a comprehensive list with examples. 1. Primitive Data Types These store single values such as numbers, text, and dates. Data Type Description Example String Sequence of characters String greeting = 'Hello, Salesforce!'; Boolean Stores true or false Boolean isActive = true; Integer Whole numbers Integer rollNumber = 1001; Long Large whole numbers Long worldPopulation = 8000000000L; Double Floating-point numbers Double pi = 3.14159; Decimal High-precision floating-point numbers Decimal price = 99.99; ID Salesforce record ID Id recordId = '0015g00000ABCD'; ...

Comprehensive List of Apex Functionalities in Salesforce

Apex is a powerful, strongly-typed, object-oriented programming language in Salesforce that allows developers to execute backend logic and automate business processes. Below is a categorized list of key Apex functionalities: 1. Object-Oriented Programming (OOP) Classes & Objects – Define classes and create objects for structured programming. Interfaces & Inheritance – Implement polymorphism and code reusability. Enums – Define a fixed set of constants. ------------------------------------------------------------------------------------------------------------------------------------ 2. Database Operations (DML - Data Manipulation Language) SOQL (Salesforce Object Query Language) – Query records from Salesforce objects. SOSL (Salesforce Object Search Language) – Perform text searches across multiple objects. DML Statements – `INSERT`, `UPDATE`, `DELETE`, `UPSERT`, `MERGE` operations on Salesforce records. Database Methods – `Database.insert()`, `Dat...

Rest API in Salesforce

  REST API is a simple and powerful web service based on RESTful principles. It exposes all sorts of Salesforce functionality via REST resources and HTTP methods. For example, you can create, read, update, and delete (CRUD) records, search or query your data, retrieve object metadata, and access information about limits in your org. REST API supports both XML and JSON. What Is REST API In Salesforce? The Salesforce REST API lets you integrate with Salesforce applications using simple HTTP methods, in either JSON or XML formats, making this an ideal API for developing mobile applications or external clients. Salesforce also supports Apex REST, which lets you create Web services on Force.com using Apex. HTTP Method Description GET Retrieve data identified by a URL. POST Create a resource or post data to the server. DELETE Delete a resource identified by a URL. PUT Create or replace the resour...