Salesforce Apex Tutorial – Chapter 1: FREE Developer course for beginners

Salesforce Apex Tutorial – Chapter 1: FREE Developer course for beginners

On September 24, 2021, Posted by , In Salesforce Apex Tutorial, With Comments Off on Salesforce Apex Tutorial – Chapter 1: FREE Developer course for beginners

Table of contents

What is Salesforce Apex?

Salesforce Apex is a powerful programming language developed specifically for the Salesforce.com platform. It is a strongly typed, object-oriented language designed to enable developers to execute flow and transaction control statements on the Force.com platform server, seamlessly integrating with the platform’s API. Apex’s syntax bears a resemblance to Java, making it accessible for those familiar with Java development. This language is pivotal in customizing Salesforce applications, as it can be triggered by various user actions such as clicking a button, accessing weblinks, activating triggers, or interacting with Visualforce pages.

The versatility of Apex extends to its availability across multiple Salesforce editions, including Enterprise, Performance, Unlimited, Developer, and Database.com. This wide availability underscores Apex’s integral role in the Salesforce ecosystem, providing developers with a robust tool for crafting custom functionalities and workflows. For those looking to master this language, numerous Apex development tutorials are available, offering step-by-step guidance to unlock the full potential of Salesforce customization and enhance the overall user experience within the platform.

You can find the Salesforce Apex Tutorial Chapter 2: Apex Environment as next chapter, sequel to this one.

Salesforce Apex Tutorial - Chapter 1: what is Apex

Features of Apex – Salesforce programming for beginners :

Salesforce Apex is loaded with several awesome features. Here’s a list of some important features:

  • The Apex programming language is strongly typed. If a schema object, like sObject, is deleted or is the wrong type, a reference to that object fails immediately.
  • Apex is a case-insensitive programming language.
  • Apex supports DML operations like Insert,Update,Delete etc.
  • Apex can execute multiple queries and DML statements concurrently.
  • Apex runs in a multitenant environment, and salesforce has set up governor limits for each user, so a user can not control shared resources. Any code that violates governor limits fails with an error message.
  • Salesforce automatically updates Apex with every new release.
  • In Apex, code coverage and efficiency of code can be checked by creating and executing Unit test cases that indicate which part of your code needs to be improved.

When Should Developer Choose Apex programming as beginner?:

Apex Code should only be written if a business scenario is too complex and can’t be implemented using the pre-built functionality provided by salesforce. Following are a few use cases where apex can be used over salesforce configuration:

  • To create web services that integrate salesforce with other applications.
  • To implement custom and complex validations on Sobjects.
  • To implement complex business processes that can’t be achieved using the out of the box salesforce functionality( Workflow, process builder, and flows)
  • To perform apex logic when a DML operation happens in Salesforce Database.
  • To set up email services which include processing the contents, headers and attachments of the email using the apex code.

Structure of Apex Programming:

Following are the actions that happen when a developer saves the code and an end-user performs some action that invokes Apex code.

Developer Action: Whenever a developer builds and saves the apex code, it compiles the code into a set of instructions that the Apex runtime interpreter can read and save that information as metadata.

End-User Action: As soon as a user event executes apex code, the server receives the compiled instructions from the metadata and sends them through the apex runtime interpreter to the platform server before returning the result.

Below is the architecture of Apex programming and how it runs on the Force.com platform.

Salesforce Apex Tutorial - Chapter 1: Apex Overview Structure of Apex
Salesforce Apex Tutorial – Chapter 1: Apex Overview Structure of Apex

What is the Syntax of Apex – Salesforce programming tutorial syntax: 

Apex Code contains many elements which are similar to other programming languages. Following are a few elements of the apex language.

Variable Declaration: Since Apex is a strongly typed language, every variable must have its own data type. Read more about variables used in Apex programming.

In Apex programming, the syntax for variable declaration is similar to that of Java. Here’s an example of how you can declare variables in Apex:

// Declaring an integer variable
Integer myInteger = 10;

// Declaring a string variable
String myString = 'Hello, Apex!';

// Declaring a list of integers
List<Integer> myList = new List<Integer>{1, 2, 3};

// Declaring a map with String keys and Integer values
Map<String, Integer> myMap = new Map<String, Integer>{'a' => 1, 'b' => 2};

In these examples, you can see that the syntax for variable declaration in Apex involves specifying the data type of the variable, followed by the variable name, and then optionally initializing the variable with a value using the = operator. Apex supports various data types, including primitive types like Integer , String , and Boolean , as well as collection types like List , Set , and Map .

SOQL Query: SOQL(salesforce object query language) directly interacts with the salesforce database and is used to fetch data from the salesforce database.

The below query is used to fetch Contact object records from the Salesforce database.

Contact[] con = [Select Id, FirstName, LastName from Contact];

Loop Statements: For iterating over a list of records, or a piece of code for a given number of times, Loop statements are used, read more here about loops.

Below is the sample code used to iterate over the list of the Contact object. 

List<Contact> listOfContact = new List<Contact>();// iteration over the contact list
For(Contact con:listOfContact ) {
//logic
};

Flow Control Statement:  Flow control statements are used when a user wants to execute or stop the execution of a piece of code on specific conditions.

Below code execute the logic if the size of the contact list is greater than zero

List<Contact> conList = [Select Id,FirstName, LastName from Contact Limit 10];
If(conList .size()> 0) {
// execute the logic if the size of the contact list is greater than zero
};

DML Statements: Data manipulation language(DML) is used to perform  Insert, update, upsert, and delete operations over records in the Salesforce database.

The below code is used to delete the account record of having the name ‘Test’.

List<Contact> conList = [Select Id,FirstName, LastName from Contact Where LastName =Test ’];
Delete conList ;

Sample code snippet

public class ApexDemoController{ 
    Public static void updateContact(){ 
        // variable declaration
        List<Contact> conList = new List<Contact>();
        // SOQL query 
        conList = [Select Id,FirstName,LastName from Contact Where LastName = 'Test'];
        List<contact> listToUpdate = new List<Contact>();
        // iteration over contact list
        for(contact con:conList){
            con.Title = 'Manager';
            listToUpdate.add(con);
        }
        // flow control statement
        if(listToUpdate != null || listToUpdate.size()> 0 ){
            // DML statement
            update listToUpdate;
        }    
        
    }
}

Above code explanation:

The ApexDemoController class contains a method named updateContact that’s designed to update specific records in the Salesforce database. This method specifically targets Contact records where the last name is ‘Test’.

First, it declares a list to hold the Contact records fetched from the database. It then runs a SOQL query to retrieve all Contacts with the last name ‘Test’, pulling their ID, first name, and last name.

Next, the method iterates through each contact in the fetched list. During this loop, it changes the title of each contact to ‘Manager’ and adds the modified contact to a new list prepared for updating.

Before updating the database, the method checks if the list prepared for updating isn’t empty. If it’s not empty, it proceeds to update the records in the database with the new title ‘Manager’. This ensures that only records that have been modified are updated, optimizing performance and avoiding unnecessary operations.

Learn Salesforce Apex programming tutorial for beginners step-by-step chapter wise approach from CRS info solutions.

FAQs

  1. How do you handle Apex transaction control and governor limits?

When discussing Apex transaction control and handling governor limits, I explain that transactions in Apex are cohesive units of work that either complete entirely or not at all, ensuring data integrity. I use ‘savepoint’ to set a rollback point and ‘rollback’ to revert to that state if something goes wrong, especially when dealing with complex DML operations.

2. How do you use trigger context variables in Apex?

Regarding the usage of trigger context variables in Apex, I highlight their crucial role in providing information about the execution context of the trigger, such as if the trigger was fired before or after an insert, update, or delete operation. I emphasize the importance of using these variables to write bulk-safe triggers, ensuring that the code properly handles multiple records at a time.

3. Can you explain the exception handling mechanism in Apex?

When it comes to exception handling in Apex, I mention that it’s akin to Java’s try-catch mechanism, allowing for the graceful handling of unexpected issues. I describe using try-catch blocks to capture exceptions and, when necessary, creating custom exceptions for more granular control over error handling in complex applications.

4. What are the best practices for writing test classes in Apex to ensure high code coverage

Discussing best practices for writing test classes in Apex, I talk about aiming for high code coverage and ensuring robust application behavior. I use the ‘@isTest’ annotation to define test classes and methods, and I stress the importance of testing not just for success but also handling edge cases and potential failures.

5. How do the ‘with sharing’ and ‘without sharing’ keywords affect data visibility in Apex?

Lastly, when asked about ‘with sharing’ and ‘without sharing’ keywords, I clarify that these control the visibility of data in Apex classes. ‘With sharing’ respects the user’s data access permissions, while ‘without sharing’ allows the code to run disregarding user-level permissions, used cautiously, typically in administrative contexts where full data access is necessary.

CRS Info Solutions offers real-time Salesforce course for beginners designed to equip learners with practical knowledge and industry skills in Salesforce. Enroll for demo today.

Comments are closed.