# Optimizing number of IF-Else statements

I need to add IF-ELSE condition in an existing method :

Statement will be like

``````If (field = X)
{ value = 'Yes'}
else if (field = Y)
{ value = 'No'}
else { value = 'NA' }
``````

Is there any way to optimize the number of if-else statements ?

• There is nothing to optimize in the above example, all three routes are leading to 3 different values of "field". Looks good. – Mahmood Nov 14 '16 at 10:46
• Val=field==x?'yes':field==y?'no':'na'; – Shravan Boddula Nov 14 '16 at 11:08

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';
``````
• By far the most common and scalable solution to long `if`/`else` chains evaluating the same condition. – Adrian Larson Nov 14 '16 at 14:06
• Unless, of course, the values are mapped to a costly resource, like queries. But I've used this technique several times, and I definitely recommend it when you get to the point where you're past the size of a reasonable ternary operator chain. – sfdcfox Nov 14 '16 at 20:49
• This may be a rookie question, but how do you do the final else using a map? – gorav Nov 16 '16 at 3:02
• @gorav Not a rookie question. You have to add a second line of code after the `get` such as `if (output == null) output = 'default value'`. – Keith C Nov 16 '16 at 11:03

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.

• I've heard that `switch` is something they couldn't do because of the old compiler, but that "it's coming." I look forward to that day. – sfdcfox Nov 14 '16 at 20:49

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.

Yes! Try:

``````Field == X ? 'Yes' : (Field == Y ? 'No' : 'NA')
``````

``````if (field = X) {
value = 'Yes'
}
else if (field = Y) {
value = 'No'
} else {
value = 'NA'
}
``````

What the others have said about Ternary operators is accurate. They are also a lot faster on compile than if/else statements, somewhere around 30%.

• And yu will never code enough of them shave as much as tenth of second off your compile time :-) Seroiusly, as programmer of X decades, we tend to frown on the terniary operator on grounds of legibility and maintainability. Writing clear, undserstandable code is paramount – Mawg Nov 15 '16 at 8:01
• Think this comes down to writing style. I have found a bunch of use cases for them. primarily in the "Int a = b != null ? b : 0; " type scenarios to avoid null reference errors. For If/else if/else scenarios I'd go the traditional approach. – Nonick Nov 16 '16 at 4:12
• in embedded development, the terniary operator is generally against company coding standards and would eb rejected at code review, but I will upvote you since your comment can be helpful to others – Mawg Nov 16 '16 at 10:06
• You guys have coding standards? I generally end up writing them :-) – Nonick Nov 17 '16 at 1:37

Not much, but is saves you one comparission; assign the default value, then check for your special cases:

``````value = 'NA'

If (field = X)
{ value = 'Yes'}
else if (field = Y)
{ value = 'No'}
``````

This is clearer, more immediately comprehensible and more maintainable then the terniary operator.

Hope for `switch` statements in future versions.

Switch Statements is now live in Salesforce (from Summer '18 Release).

Syntax:

``````switch on expression {
when value1 {       // when block 1
// code block 1
}
when value2 {       // when block 2
// code block 2
}
when value3 {       // when block 3
// code block 3
}
when else {       // default block, optional
// code block 4
}
}
``````

Simple Example:

``````switch on i {
when 2 {
System.debug('when block 2');
}
when null {
}
when else {
System.debug('default ' + i);
}
}
``````