Simple Conditional Statements in Apex
Conditional statements will help us guide or advise our code based on whether certain conditions are met to perform specific actions. In Apex, we mostly work with if-else statements and switch statements.
If-Else Statements
let us execute one piece/block of code. if a condition is true and another if it is false, based on our business requirement or use case. Below is a very basic example to understand it:
public class TemperatureCheck {
public static void checkTemperature(Integer temperature) {
if (temperature > 25) {
System.debug('It is warm outside.');
} else {
System.debug('It is cool outside.');
}
}
}
In this piece of code, if the temperature is above 25 degrees, it will log/execute that it is warm; otherwise, it will log that it is cool.
Switch Statements
Switch statements can make our code more clean and neat when we have multiple values to check against one variable based on our different business needs. Below is a simple example using user roles:
public class RoleMessage {
public static void showRoleMessage(String role) {
switch on role {
when 'Admin' {
System.debug('Welcome, Admin!');
}
when 'User' {
System.debug('Hello, User!');
}
when else {
System.debug('Role not recognized.');
}
}
}
}
The above example displays a clear and straightforward method to handle different cases. The when else clause serves as a catch-all for any roles that don’t match the given cases then it will execute.