6

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 ?

  • 2
    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
12

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
  • 3
    @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
6

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.

  • 1
    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
3

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.

2

Yes! Try:

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

Instead of:

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

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%.

  • 1
    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
  • 1
    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
  • 1
    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
1

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.

1

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 {
       System.debug('bad integer');
   }
   when else {
       System.debug('default ' + i);
   }
}

Please check Salesforce documentation on Switch for more information.

0

A drawback of the ternary solution is when the values to be assigned are function results. I don't know about Apex, but in most languages all values that could be assigned are evaluated even if only one of them is used. This is, at best, a performance problem and worse if the functions have any side-effects.

  • 4
    I don't believe I"ve ever seen a language that has this behavior. Can you verify your statement? – IllusiveBrian Nov 14 '16 at 13:32
  • Apex does lazy evaluation. – Adrian Larson Nov 14 '16 at 13:37
  • 4
    I remember experiencing the function call behaviour in Visual Basic a long time ago. In Apex only the paths taken are evaluation so there is no performance loss or extra risk using the ternary solution. However, with 3 outcomes I think it makes the code hard to use so I wouldn't use it in that case. – Keith C Nov 14 '16 at 13:45
  • 1
    This is interesting but it doesn't really answer the question. Also could you say which languages you've seen this in Paul, I don't think I've ever seen any either - I agree with @IllusiveBrian – Brad Thomas Nov 14 '16 at 14:11
  • This is not true in Apex. Only the branch taken in the ternary operator is evaluated, while the other side is not. I've actually written code that proved this to myself, because it's not documented. – sfdcfox Nov 14 '16 at 20:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.