We are seeing AL Language getting mature day-by-day, and just like other programming languages (C#, C++, Java, etc) - AL also supports Ternary Operator since wave 2 (BC25).
Ternary Operator makes your code more compact and readable in certain scenarios, but it works just like IF-ELSE statements.
So, the question remains the same - Should I use IF-ELSE or the ternary operator?
Both approaches help in assigning values based on conditions, but they differ in readability, use cases, and limitations.
Let’s break it down.
Ternary Operator – The Compact Way
The ternary operator allows you to evaluate a condition and return a value in a single line.
A simple syntax for ternary operator is -
Let’s look at some examples.
Example 01: Simple Assignment
This is same as -
Output:
- If Item exists → returns Item Description
- If not → returns blank
Example 02: Default Value Handling
Output:
- If previous line exists → increments Line No.
- If not → starts from 10000
Example 03: Conditional Calculation
- Returns 10 if Amount > 1000
- Otherwise returns 0
Best for: Simple conditions, single assignments, default values.
IF-ELSE – The More Readable Approach
The traditional IF-ELSE block is more verbose but gives better control and clarity.
Example 01: Same Logic Using IF-ELSE
Where Ternary Falls Short
While ternary is powerful, it is not suitable in all scenarios. For example -
Example 01: Multiple Statements
Ternary cannot handle multiple operations at once. This is one of the most important drawbacks of using ternary operator.
Example 02: Complex Conditions
This becomes difficult to read and maintain. The developers who have never worked on the Ternary operator, will get difficulty understanding such complex conditions.
Which One Should You Use?
Use ternary whenever possible → it’s cleaner and reduces code lines.
Use IF-ELSE when you need → multiple statements, validations, or complex logic.
Think of it this way:
Ternary = Simple, Clean, Compact
IF-ELSE = Flexible, Readable, Controlled
The decision should be based on readability and maintainability, not performance.
Conclusion
I generally use Ternary Operator a lot - using it for finding the last Line No., or assigning Description value when Code or "No." field is validated. Everyone should use ternary operator whenever and wherever they can, but it should be readable and understandable.
For the developers who never worked on Ternary Operator before, it should not be a headache for them to understand simple conditions.
code snippet widget