Optimizing number of IF-Else statements
Not relevant if only a couple of if/else, but if there are many, sometimes creating a map is a good way to go:
private static final Map<String, String> MY_MAP = new Map<String, String>{
'abc' => '123',
'def' => '456',
'ghi' => '789',
...
};
....
String output = MY_MAP.get(input);
This code can be easier to read and understand and also helps performance because the result is a direct map lookup rather than multiple if
condition evaluations.
In my company we no longer put curly brackets round single statements that fit easily on the same line as the condition to cut down the visual noise so would code the logic in the question like this:
if (field == X) value = 'Yes';
else if (field == Y) value = 'No';
else value = 'NA';
There's a few things around if
statements you should probably consider.
The elephant in the room (in my opinion) is that Apex does not support switch
statements.
Given you appear to be updating a value based on another fields value, you may want to consider using clicks, not code. As a rule of thumb, use:
- Process Builder when you have multiple if/then statements
- Workflow when you have a single if/then statement
If you must use Apex, you can use an inline-if statement, otherwise known as a ternary operator as outlined in @salesforceMann's answer which you can test using the below code that will debug "N/A".
String field = 'z';
String result = field == 'x' ? 'Yes' : field == 'y' ? 'No' : 'N/A';
System.debug(result);
Compared with the following:
String field = 'z';
String result;
if (field == 'x') {
reuslt = 'Yes';
}
else if (field == 'y') {
result = 'No';
}
else {
result = 'N/A';
}
System.debug(result);
You can immediately see that you're saving, relatively, a lot of space and you'll save a bit on heap allocation.
Not to steal @salesforceMann's thunder here, but wanted to add a bit more for something this simple.
The Summer '18 (v43.0) release is planned to include native switch
statement support in Apex.
In this scenario the minimal code would go from:
if (field == X) {
value = 'Yes';
} else if (field == Y) {
value = 'No';
} else {
value = 'NA';
}
To:
switch on field {
when 'X' {
value = 'Yes';
}
when 'Y' {
Value = 'No';
}
when else {
value = 'NA';
}
}
Note that I had change the variables X
and Y
to literals in the switch statement. Otherwise you get the error:
'when identifier' is only allowed for switch on enum
Please consider voting for the idea Add support for final variables in switch statement when clauses
In this specific case you are unlikely to see any improvement. Especially when compared to a Map based lookup solution. However, there may be more complicated scenarios where a switch statement will make the code easier to read. It might just be a case of moving X
and Y
into an enum so they could be used directly in the switch conditions.