Apex Decision Making in Salesforce

Apex Decision Making in Salesforce

On January 16, 2024, Posted by , In Salesforce Apex Tutorial, With Comments Off on Apex Decision Making in Salesforce

Table of Contents

Introduction

A decision-making structure contains one or more conditions that are to be evaluated by the program, along with a statement or statements that should be executed if the condition is true, and maybe other statements if it is false.

Here, we will discuss the structure of decision-making and conditional statements in the apex. In order to control how the execution flows when a condition is met, decision-making is necessary.

Following is the structure of decision-making used in most programming languages.

CRS Info Solutions offers a comprehensive and dynamic Salesforce online course career building program for beginners, covering admin, developer, and LWC concepts. This course features immersive real-time projects, interactive hands-on learning, detailed daily notes, essential interview questions, thorough certification preparation, and strategic job prep guidanceEnroll for a free demo today!

Control Statements

Control statements are fundamental to any programming language, and Salesforce Apex is no exception. They allow developers to control the flow of execution within a program based on certain conditions or by iterating over collections of data. Apex provides several types of control statements, including conditional statements (if-else), loop statements (for, while, do-while), and branching statements (break, continue, return). Understanding these control structures is essential for writing efficient, readable, and robust Apex code.

Apex Decision Making Flow-Chart-1
// Example 1: Simple If Statement
if (accountBalance > 0) {
    System.debug('Your account is in good standing.');
}

// Example 2: If-Else Statement
if (temperature < 0) {
    System.debug('It is freezing outside!');
} else {
    System.debug('It is not freezing outside.');
}

// Example 3: If-ElseIf-Else Statement
if (score >= 90) {
    System.debug('Grade A');
} else if (score >= 80) {
    System.debug('Grade B');
} else if (score >= 70) {
    System.debug('Grade C');
} else {
    System.debug('Grade D');
}

// Example 4: Nested If Statement
if (loggedIn) {
    if (userRole == 'Admin') {
        System.debug('Welcome, Admin!');
    } else {
        System.debug('Welcome, User!');
    }
}

Description of above ER diagram/ structure as follows:

If statement:

The if statement in Apex Salesforce is a fundamental control structure used to execute code conditionally. It evaluates a boolean expression, and if the expression is true , the code within the block is executed. This allows developers to introduce decision-making into their applications, handling different conditions and behaviors dynamically based on specific criteria.

For example:

if ([Boolean_condition]) {
    // your logic
}

If-else statement:

The if-else statement in Apex Salesforce enhances decision-making in code by allowing not only for actions based on a true condition but also for an alternative path if the condition is false. This structure ensures that one of two possible blocks of code will execute, depending on the outcome of the condition tested. It is ideal for handling binary decisions, providing a clear path for both fulfilling and non-fulfilling conditions.

For example,

Integer x, sign;
// Your code
if (x <= 0) {
    if (x == 0) {
           sign = 0; 
    } else  {
           sign = -1;
    }
}

If-elseIf-else:

The if-elseIf-else statement in Apex Salesforce extends the basic if-else logic to handle multiple conditions sequentially. It allows developers to specify additional conditions using elseIf clauses, each with its own block of code that executes only if its condition is true. This structure is particularly useful for branching logic where several distinct paths or outcomes may be based on different criteria, ensuring that each condition is evaluated in order until one is met, or the else block executes as a default.

For example:

Integer x, sign= 2;
// Your code
if (x <= 0) {
           sign = 0; 
    } elseif  {
           sign = -1;
    }else {
       sign = 2;
}

Nested if statement: 

The nested if statement in Apex Salesforce involves placing one if statement inside another, allowing for more complex decision trees within a single block of code. This structure is useful for checking multiple conditions in a hierarchical manner, where the outcome of one condition may lead to another set of conditions being evaluated. Nested if statements are crucial when dealing with scenarios that require detailed and layered decision-making logic in your Salesforce applications.

For example:

if boolean_expression_1 {
/* Executes when the boolean expression 1 is true */
  if boolean_expression_2 {
  /* Executes when the boolean expression 2 is true */
  }
  Else{
    //* Executes when the boolean expression is false
   }
}

Conditional Statements in Apex

Conditional statements in Apex enable you to execute different sections of code based on certain conditions. The most common conditional statement is the if-else statement.

Example:

if (score > 90) {
    System.debug('Excellent');
} else if (score > 75) {
    System.debug('Very Good');
} else {
    System.debug('Good');
}

This simple example demonstrates how Apex can execute different blocks of code depending on the value of the score variable. Such conditional logic is crucial for making decisions within your applications, allowing for dynamic responses to varying inputs.

Loop Statements in Apex

Loop statements are used to repeat a block of code multiple times. Apex supports several types of loops, including for , while , and do-while .

Example of a for loop:

for (Integer i = 0; i < 10; i++) {
    System.debug('Iteration: ' + i);
}

This loop will execute the System.debug statement 10 times, printing numbers 0 through 9. Loops are particularly useful for processing collections of data, such as lists and sets, which are common in Salesforce data manipulation.

Branching Statements in Apex

Branching statements allow you to alter the flow of execution in a program dynamically. Apex supports break , continue , and return statements.

Example using break :

for (Integer i = 0; i < 100; i++) {
    if (i == 5) {
        break; // Exits the loop if i is 5
    }
    System.debug('i = ' + i);
}

In this example, the loop will terminate prematurely when i equals 5. Such control is useful for stopping execution when a condition is met, without processing further unnecessary iterations.

Each of these control statements plays a crucial role in developing Apex applications. They provide the structure needed to handle complex logic, manage data processing, and respond dynamically to the changing states within Salesforce environments. Understanding and using these control structures effectively will greatly enhance your ability to write sophisticated and efficient Apex code.

Read the previous chapter Constants and the next chapter Loops.

For those looking for Salesforce learning, CRS Info Solutions provides an extensive Salesforce training program designed to enhance your skills and career opportunities. Explore our Salesforce training in Hyderabad to gain practical, hands-on experience, real-time projects included. Enroll for free demo today!

Comments are closed.