Skip to content
Home » Blog Archive » Exploring the “?” Symbol in Salesforce Apex: The Ternary Operator

Exploring the “?” Symbol in Salesforce Apex: The Ternary Operator

Hey fellow Salesforce developers! In this blog post, I’ll be sharing with you how to use the “?” symbol as a ternary operator, which is part of my series on “Exploring the “?” Symbol in Salesforce Apex”.

If you’re new to ternary operators, don’t worry – I’ll break it down in simple terms. But before we get into that, if you need a refresher on conditional statements in Apex, including a basic overview of ternary operators, make sure to check out my previous blog: “Beginner’s Guide to Salesforce Apex: Navigating Conditional Statements”. It’s a great starting point that covers the essentials of if, else if, switch, and of course, the ternary operator.

Now, back to ternary operators. As a starting point, here’s a simple definition for the ternary operator.

In this article, we’ll explore the syntax of the ternary operator and share some tips for using it effectively. By the end of this post, you’ll be equipped to write cleaner, more efficient, and more maintainable code in your Apex projects using the ternary operator. So, let’s dive in and get started!

What is the ternary operator?

The ternary operator is a shorthand way of writing conditional statements in Apex. Instead of using an “if” statement with a block of code for each condition, you can use the ternary operator to write the same logic in a single line.

Let’s write an example where we set a variable called ‘passName’ to either ‘Adults pass’ or ‘Kids pass’ based on the ‘ageValue’ using both the regular if-else statement and the ternary operator, so we can compare between the two approaches.

Example using if-else statement

Integer ageValue=20;
String  passName;
....
if(ageValue>18){
  passName = 'Adults pass';
}else{
  passName = 'Kids Pass'; 
}
System.debug('Check passName: ' + passName);

Example using the ternary operator

Integer ageValue = 20;
String  passName;
....

passName = ageValue>18?'Adults pass':'Kids Pass';
System.debug('Check passName: ' + passName);

The ternary operator output sample

Salesforce apex ternary operator in action

What do you think? Pretty amazing, right? Having lots of if-else statements in your code can make it hard to read. That’s where the ternary operator comes in handy. It can help improve code readability, especially for simple conditions. I highly recommend giving it a try.

Let me explain to you the ternary operator syntax in more details.

Syntax

Boolean_expression ? expression_if_true : expression_if_false
ParameterExplanationExample
Boolean_expressionIt is the logical check we want to perform and it is evaluated first to either true or false. if it’s true, the expression_if_true is executed; otherwise the expression_if_false is executed.
ageValue>18

In the example we were checking wether ageValue is greater than 18 or not.
expression_if_trueIt is the expression that is executed if the Boolean_expression is evaluated to true. The value of this expression execution is returned and can be assigned to a variable or used as part of another expression‘Adults pass’

In the example, this expression was a simple fixed string.
expression_if_falseIt is the expression that is executed if the Boolean_expression is evaluated to false. The value of this expression execution is returned and can be assigned to a variable or used as part of another expression‘Kids pass’

In the example, this expression was a simple fixed string.
The Ternary Operator Syntax Explanation

Tips for using ternary operator

Let’s point some tips to keep in mind while using the ternary operator to keep your code readable and easy to maintain :

Keep the logic simple

  • The ternary operator is best suited for simple conditional statements. For more complex logic, it’s better to use traditional if-else statements.
  • For example, the following if-else statements would be better suited to traditional if-else statements rather than the ternary operator.
if (Boolean_expression1) {
    // Do something
} else if (Boolean_expression2) {
    // Do something else
} else {
    // Do something else if both Boolean_expression1 and Boolean_expression2 are false
}

Use parentheses & be consistent

  • Adding parentheses around the condition can help make the code more readable and prevent unexpected behaviour.
  • Consistency is key when it comes to code readability and maintainability. If you choose to use parentheses with the ternary operator, make sure to communicate this to your team to ensure consistency throughout the codebase.

Sample without parentheses (not recommended)

Boolean boolVar1=true;
Integer ageValue = 12;
String result = boolVar1 && ageValue>15?'True Value':'False Value';

Sample with Parentheses (recommended)

Boolean boolVar1=true;
Integer ageValue = 12;
String result = (boolVar1 && ageValue>15)?'True Value':'False Value';

Avoid nesting

  • While it’s possible to nest ternary operators, it can quickly become difficult to read and maintain. It’s generally better to use if-else statements in these cases.

Sample of nested ternary operator (not recommended)

Integer x=5;
Integer y=9;
Integer z=11;

String result = (x > y) ? ((x > z) ? 'x is the largest number' : 'z is the largest number') : ((y > z) ? 'y is the largest number ' : 'z is the largest number');

Sample using regular if-else statements (recommended)

Integer x=5;
Integer y=9;
Integer z=11;
String result='';

if (x > y && x > z) {
    result = 'x is largest';
} else if (y > x && y > z) {
    result = 'y is largest';
} else {
    result = 'z is largest';
}

General Tips

  1. Use descriptive variable names: when declaring variables, use meaningful names that are self explanatory for the variable usage. For example, avoid using variable names as x,y,z and try using names as ageValue,isActive, etc.. [Notice the camelCase used for variable names]. This will make your code easier to read and understand.
  2. Use comments to explain your logic: It is a good practice to add meaningful comments in your code to explain the logic you are implementing. These comments will be helpful for other developers and for yourself. Believe me, if you write a code and leave it for two months, and when you come back to edit it, you will thank yourself for adding those comments.

Conclusion

In conclusion, the ternary operator is a powerful tool that can help you write clean and efficient code in Salesforce Apex. By following best practices, such as keeping your logic simple and being consistent with your code style, you can make the most of this operator and improve your coding skills.

I hope you found this blog post helpful and learned something new about the “?” symbol in Salesforce Apex. Remember, don’t be afraid to try using the ternary operator in your code. It might seem intimidating at first, but with practice, you’ll be able to master it and write even better code.

Stay tuned for more posts exploring the different usages of the “?” symbol in Salesforce Apex. Don’t forget to follow me on social media for updates and more tips on Salesforce development.

Thanks for reading, and happy coding! Check out my Youtube Channel!

Join the conversation

Your email address will not be published. Required fields are marked *