Is there a cleaner way to check for a condition to set a variable then to use a bunch of IF statements?

451 views Asked by At

I am looking to possibly shorten my code. It seems super redundent but I am not sure how else I would be checking for a specific condition to set a variable besides a large IF statement?

IF MaxContaminationCode := -2 THEN
        ContaminationClass := '000';
    ELSIF MaxContaminationCode := -1 THEN
        ContaminationClass := '00';
    ELSIF MaxContaminationCode := 0 THEN
        ContaminationClass := '0';
    ELSIF MaxContaminationCode := 1 THEN
        ContaminationClass := '1';
    ELSIF MaxContaminationCode := 2 THEN
        ContaminationClass := '2';
    ELSIF MaxContaminationCode := 3 THEN
        ContaminationClass := '3';
    ELSIF MaxContaminationCode := 4 THEN
        ContaminationClass := '4';
    ELSIF MaxContaminationCode := 5 THEN
        ContaminationClass := '5';
    ELSIF MaxContaminationCode := 6 THEN
        ContaminationClass := '6';
    ELSIF MaxContaminationCode := 7 THEN
        ContaminationClass := '7';
    ELSIF MaxContaminationCode := 8 THEN
        ContaminationClass := '8';
    ELSIF MaxContaminationCode := 9 THEN
        ContaminationClass := '9';
    ELSIF MaxContaminationCode := 10 THEN
        ContaminationClass := '10';
    ELSIF MaxContaminationCode := 11 THEN
        ContaminationClass := '11';
    ELSIF MaxContaminationCode := 12 THEN
        ContaminationClass := '12';
    END_IF

With this code, I am checking to see if a calculated value (MaxContaminationCode), which is an INT, is a specific value. If it is the specific value set "ContaminationClass" (which is a string), to the respective value.

2

There are 2 answers

3
Guiorgy On BEST ANSWER

In general, if you have many different cases, then it is preferable to use the CASE statement ('switch' in other languages) as DrBwts said. Also, as Gereon said, in your example you could decrease the cases you check. So for your example it would look something like this:

CASE MaxContaminationCode OF
-2:
  ContaminationClass := '000';
-1:
  ContaminationClass := '00';
0..12: // if you ONLY want 0 to 12, otherwise use ELSE here
  ContaminationClass := INT_TO_STRING(MaxContaminationCode);
END_CASE
2
Sergey Romanov On

I agree with suggestion above. But to make it even more compact (-2 lines).

ContaminationClass := INT_TO_STRING(MaxContaminationCode);
IF MaxContaminationCode = -2 THEN
    ContaminationClass := '000';
ELSIF MaxContaminationCode = -1 THEN
    ContaminationClass := '00';
END_IF