Apex Syntax Basics
This post teaches the core Salesforce Apex language fundamentals you must know: syntax basics, classes/methods/constructors, method overloading, collections (List/Set/Map), SOQL + DML, exception handling, access modifiers, and the #1 bulk pattern (Ids → Query → Map → Apply → DML). It also includes a beginner mistake checklist and interview questions.
Salesforce Apex Language Fundamentals & Syntax
What Is Apex?
Apex is Salesforce’s strongly typed, Java-like server-side language used to build business logic, automation, and integrations on the Salesforce platform. Because Salesforce is multi-tenant, Apex must respect governor limits (SOQL, DML, CPU time, heap, etc.).
Common mistakes
-
Writing Apex like Java without thinking about limits
-
Doing SOQL/DML repeatedly inside loops
Apex Basic Syntax (Core Notations)
Apex fundamentals include types, variables, conditionals, loops, and expressions.
-
Not handling
nulland blank strings -
Confusing
DatevsDatetime -
Overusing debug logs in production
Apex Classes, Methods, and Constructors
Apex code lives inside classes.
-
Methods do work and may return values
-
Constructors initialize object state
-
No “free functions” outside classes
-
staticbelongs to the class; instance members belong to the object -
thisrefers to the current instance
Common mistakes
-
Putting too much logic in constructors
-
Using instance state when a static utility method is better (and vice-versa)
Method Overloading in Apex
Method overloading means the same method name with different parameters.
-
Confusing overloading with overriding
-
Creating ambiguous overloads with similar parameter types
Apex Collections: List vs Set vs Map
Collections are key to writing bulk-safe Apex.
-
List: ordered, duplicates allowed
-
Set: unique values only
-
Map: key → value lookup (fastest for searching)
-
Searching lists repeatedly instead of using maps
-
Forgetting Sets remove duplicates automatically
-
Holding too much in memory (heap limit)
Map in Apex
What a Map Is (and Why It Matters)
A Map stores unique keys mapped to values. Maps are essential for bulkification because they avoid repeated scanning and nested loops.
Why Maps Are Master-Level
Maps help you:
-
avoid SOQL in loops
-
avoid nested loops (better CPU usage)
-
“join” data efficiently (parent ↔ child)
-
build scalable triggers, batches, and APIs
Common Map Types
// 1) Id -> SObject (most common)
Map<Id, Account> acctById = new Map<Id, Account>([
SELECT Id, Name FROM Account LIMIT 10
]);
// 2) String -> Id (external keys / json keys)
Map<String, Id> oppByApplicationId = new Map<String, Id>();
// 3) Id -> List<Child> (grouping)
Map<Id, List<Contact>> contactsByAccountId = new Map<Id, List<Contact>>();
Core Map Operations
-
put()overwrites existing value if key exists -
get()returnsnullif not found -
iteration order isn’t guaranteed
The #1 Apex Bulk Pattern (Mini Diagram)
Ids → Query once → Map → Apply → DML once
Bulkification Example (Bad vs Good)
Bad (nested loops)
Standard Trigger Shape (Bulk-Safe)
Grouping Pattern: Map<Id, List<Child>>
Relationship Query Shortcut (No Manual Grouping)
Map Pitfalls Checklist
-
Null-check
map.get(key) -
Don’t assume iteration order
-
Watch heap usage for large maps
-
Prefer maps for lookups instead of scanning lists
sObjects, SOQL, and DML
SOQL reads data; DML writes data.
Partial Success DML
-
SOQL/DML inside loops
-
Querying too many rows/fields
-
Not handling partial failures when needed
Exceptions and Error Handling
Use try/catch/finally to handle failures safely.
-
Catching only
Exceptionand hiding details -
Swallowing exceptions without any logging/handling
Access Modifiers (Visibility)
Use modifiers to control access:
-
private: only inside the class -
protected: class + subclasses -
public: available in the org -
global: needed for managed packages / broad exposure
Also common:
-
static: shared per transaction -
final: cannot be changed or overridden
Common mistakes
-
Making everything
public -
Using
globalwhen not required
Key Apex Keywords to Know
-
extends: Inheritance — a class inherits fields/methods from a parent class. -
implements: Interface contract — a class must provide implementations for all interface methods. -
virtual: Allows a class/method to be overridden in a child class (Apex requiresvirtualorabstractto override). -
override: Marks a method that replaces a parent class’s virtual/abstract method implementation. -
with sharing: Enforces record-level sharing rules (who can see which records) for that class. -
without sharing: Ignores sharing rules (runs in system context for sharing). Still doesn’t automatically bypass CRUD/FLS. -
throw: Manually raises an exception to stop normal execution and signal an error. -
try / catch / finally: Error handling —tryruns code,catchhandles exceptions,finallyruns always (cleanup/logging). -
new: Creates a new instance (object) likenew Account(...)ornew MyClass(). -
return: Sends a value back from a method (or exits the method early).
Mini End-to-End Demo (Real Apex Shape)
Validate → build list → DML → handle error.
FAQ / Interview Questions
-
What’s the difference between
staticand instance members in Apex? -
Why are Maps critical in trigger code? Show the bulk pattern.
-
What happens if you run SOQL or DML inside a loop?
-
insert listvsDatabase.insert(list, false)— what’s the difference? -
When do you use
with sharingvswithout sharing? -
Method overloading vs overriding — how are they different?
-
What’s your strategy for handling DML errors in bulk operations?
Conclusion
If you master these fundamentals—especially collections and the bulk pattern (Ids → Query → Map → Apply → DML)—you’ll write Apex that is faster, safer, and production-ready.
