0

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.