Salesforce Apex If-Statement with OR-Logic

352 views Asked by At

I like to write and If-Statement in Apex Code with the following logic:

The Variable myVariableString can be blank, empty, ValueA, ValueB, ValueC or, and here I asume, because the Variable gets its Value from an external OCR-ML-API, ValueN could appear.

The If-Statement should be true and the following break should be executed, if myVariableString is blank or myVariableString is not ValueA or ValueB.

Or

The If-Statement should be true and the following break should be executed, if myVariableString is blank or myVariableString is ValueC or any other ValueN then ValueA and ValueB.

So I tried the following:

if (String.isBlank(fineCategory) || (fineCategory.containsIgnoreCase('ValueC'))) {
              break;
            }

Which is currently the best working if-Statement but would be false and the break is not executed when a possible ValueN appears.

if (String.isBlank(fineCategory) || !fineCategory.containsIgnoreCase('ValueA') || !fineCategory.containsIgnoreCase('ValueB'))) {

I bet, that I just need to add the ( and ) at the correct position.

Maybe someone can help me out. All the best, Sven

1

There are 1 answers

0
Gabriel Loch On
  List<String> notAllowedValues = new List<String>{'valuea', 'valueb'};

  for(String myVariableString  : new List<String>{null, '', 'ValueA', 'ValueB', 'ValueC', 'ValueN'}){
    if(String.isBlank(myVariableString ) || notAllowedValues.contains(myVariableString.toLowerCase())){
      break;
    }

    /* ... */
  }

Don't lock the allowed (or unalloed) options on a exclusive statment, think that today you have two unallowed options, tomorrow you can have 50, if you add a if statment for every single option, think on the size of it.

Create a list (wich could be retrieved from a object like a custom setting, custom label or custom metadata) and apply your rule with it. So as your application grows, your code will hold it and will be easy to read it.