Live Salesforce Training & Pre-Recorded Videos Available | Admin • Development • LWC • Agentforce • Data 360 • Integration • Job-Ready Sessions | Contact us for more info +91 - 709 7777 111
Welcome to SfdcIndia

Salesforce Apex

Gallery Feature

Salesforce Apex

Salesforce Development

Salesforce Apex: A Practical Guide for Developers

Learn where Apex fits in Salesforce, when to use it and how to write reliable code for everyday business needs.

01 What Is Salesforce Apex?

Apex is Salesforce’s programming language for writing custom business logic. It runs on Salesforce servers and uses syntax similar to Java.

  • Classes and methods: Organize reusable business logic.
  • Triggers: Run logic before or after supported record changes.
  • SOQL and SOSL: Query or search Salesforce records.
  • DML: Insert, update, delete and restore records.

02 Is Apex Still Required in the AI Era?

Yes. Apex remains useful for custom business logic, integrations and complex data processing. Every requirement does not need code.

  • AI can help generate code, but developers must review and test it.
  • Business rules still need predictable execution and permission checks.
  • LWC can call Apex when it needs custom server-side logic.
  • Flow and Agentforce can use Apex actions through @InvocableMethod.

Practical takeaway: Learn Apex fundamentals so you can understand, secure and maintain the code that AI helps create.

03 When Was Apex Introduced, and Why?

Salesforce announced Apex in 2006, with its release following in 2007.

  • To support business requirements beyond standard configuration.
  • To let developers run custom logic on Salesforce servers.
  • To work directly with Salesforce records and transactions.
  • To build reusable logic and custom integrations.

04 When Should You Choose Apex? Where Is It Used?

Choose Apex when standard features or Flow cannot meet the requirement cleanly, or when you need greater control over processing.

Requirement Suitable Approach
Simple field calculations or validation Formula fields and validation rules.
Straightforward business automation Flow.
Complex calculations or transaction logic Apex classes and triggers.
Custom server logic for a screen LWC with Apex.
Background processing or custom APIs Queueable Apex, Batch Apex or Apex REST, as appropriate.

Where Apex Is Used

  • Record automation and custom business services.
  • LWC and existing Visualforce controllers.
  • Invocable actions for Flow and Agentforce.
  • External integrations and custom API endpoints.
  • Scheduled jobs and background processing.

05 How and Where Do You Build Apex?

Use the Developer Console to write and test Apex directly in Salesforce. Practise in a sandbox or Developer Edition org.

  • Click the Setup gear → Developer Console.
  • Select File → New → Apex Class and enter a class name.
  • Write your Apex logic and save the class.
  • Use Debug → Open Execute Anonymous Window to call your method for a quick check.
  • Create a test class and run it from Test → New Run.
  • Check the test results and debug logs, then fix any errors.

Developer Console access depends on your permissions. Create and edit Apex in a development org; production code changes require deployment.

06 Apex Best Practices

  • Process records in bulk. Design code for multiple records, not just one.
  • Keep SOQL and DML outside loops. Query once where possible and save collections together.
  • Use Lists, Sets and Maps. Avoid repeated searches and unnecessary nested loops.
  • Keep triggers small. Move reusable logic into handler or service classes.
  • Prevent repeated processing. Check changed values and design updates so they do not keep triggering themselves.
  • Set security explicitly. Choose sharing and database access modes deliberately. with sharing alone does not enforce object and field permissions; defaults vary by API version.
  • Protect integrations. Use Named Credentials and External Credentials instead of storing passwords or tokens in code.
  • Use bind variables. Validate inputs and avoid unsafe dynamic SOQL.
  • Test real outcomes. Cover bulk records, invalid inputs, restricted users and failed callouts using mocks.
  • Handle errors carefully. Log useful details without exposing secrets or silently hiding failures.

07 Common Apex Errors

Error or Issue Practical Fix
Too many SOQL queries: 101 Reduce repeated queries. Check loops, recursion and other automation in the same transaction.
Too many DML statements: 151 Collect records and perform DML outside loops.
Attempt to de-reference a null object Check for null values before reading fields or calling methods.
List has no rows for assignment to SObject Query into a list and check whether it is empty.
FIELD_CUSTOM_VALIDATION_EXCEPTION Check the validation rule and provide valid data.
MIXED_DML_OPERATION Separate setup-object changes, such as User updates, from business-record changes using appropriate transactions.
UNABLE_TO_LOCK_ROW Reduce competing updates to the same records; serialize work or use controlled retries where appropriate.
You have uncommitted work pending Plan callouts before pending DML or move the work into a separate transaction.
Apex CPU time limit exceeded Reduce repeated work, nested loops and automation recursion.
Apex heap size too large Retrieve fewer fields and records, reduce payloads and process smaller chunks.

08 Limitations and Solutions

Apex runs on a shared platform. Governor limits control the resources a transaction can use.

Limit or Constraint Solution
SOQL queries: normally 100 per synchronous transaction Combine queries and use collections. Many asynchronous contexts allow 200; check the execution context.
DML statements: 150 per transaction Insert or update collections instead of individual records.
CPU time: normally 10 seconds synchronously Simplify processing. Move suitable work to asynchronous jobs, where the usual CPU allowance is 60 seconds.
Memory and record-volume limits Use selective queries and smaller batches. Batch Apex processes large workloads in separate transactions.
Asynchronous execution is not immediate Use it for work that can finish later. Monitor jobs and handle failures.
Apex does not build the browser interface Use LWC for the screen and Apex for custom server logic.
Production deployment requires passing tests and coverage Meet the coverage rules for the selected test level and use assertions to verify the results.

Remember: Limits are shared by work in the same transaction. A new class or method does not reset them, and governor-limit exceptions generally cannot be recovered from with try/catch.

09 Real-Time Use Cases

Use Case What Apex Does
Student enrolment Applies complex fee rules and creates related enrolment records.
Sales commission Calculates commissions using business-specific rules.
ERP integration Sends order data to an external system and processes responses.
Service management Applies complex case-routing or escalation logic when standard tools are insufficient.
Large record updates Uses Batch Apex to process records in manageable groups.
Agentforce action Checks availability or updates records through a controlled custom action.
Custom API Exposes a business operation through an authenticated Apex REST endpoint.

10 Key Points to Remember

  • Apex handles server-side business logic.
  • Choose standard features or Flow when they meet the requirement.
  • Write code for multiple records from the start.
  • Understand SOQL, DML and governor limits.
  • Set sharing and data-access security deliberately.
  • Use asynchronous processing only when it fits the requirement.
  • Passing tests and meaningful assertions matter more than coverage alone.
  • Review AI-generated code before using it.
Published by SFDCINDIAUpdated: