AL Code Analyzer CASE Statement

Created on 18 May 2018  路  10Comments  路  Source: microsoft/AL

Hello,

The AL Code Analyzer says that we should replace a IF statement with a CASE statement also when there is not really needed.

In this example, we have only 1 simple condition: IF ... THEN ... ELSE. I think CASE should be used when we have multiple conditions.

If we replace the IF with a CASE statement, the code is less readable because we will have a CASE inside of another CASE and also more lines of code compared to the simple IF condition.

Please see attached screen.
if then else compared to case

Is it possible to improve the code analyzer to not give warning for this case ?

Thanks,
Andrei Lungu

bug ships-in-future-update

Most helpful comment

@bvbeek - I disagree :) - I find this much more readable than multi-nested ifs and elses :)

All 10 comments

Hi @andreilungu,
The rule works as expected since your code actually contains a if-else if-else you have just indented the code so it is a bit harder to spot.
If you don't like the current behavior then you can turn off the rule with the use of rulesets. See here

Hi Thomas,

I think it's to easy to turn of the rule, take a look at this example.
Please can you write down the expected case-statement?

image

one example:
image

@gudrunleos thanks for the suggestion, this is the only way to solve it, with a case true of but this is really horrible code.

I hope everyone does not like this code.

@bvbeek - I disagree :) - I find this much more readable than multi-nested ifs and elses :)

I have to agree with @gudrunleos

I have used CASE TRUE OF on countless occasions. I even find myself refactoring existing buggy code to use it to fix the bugs.

Maybe I need to explain why this is horrible code 馃槃

1. The sorting of the case-list can be important (performance),
If the first case-option is true (in most cases) then should this always be the first case.
If someone else add a new option above, you can have performance issues.

2. The if-statement has two options
In case of more than 2 the case-statement would be needed (only for the readability).

3. This is mis-using a case-statement
The case statement is designed to check a value against another value/listed-value.
In this case you compare a return value to a case-value.

And why this is not so horrible code...

  1. This is the beauty of the case true of statement - you can decide the priority of the conditions and simplify each one of them.
  2. Of course you use an if statement if there are only two options.
  3. And the list of values can be calculated one by one - right?

Good coding 馃槃

We have changed how this rule works. Please try a docker image next week to see if the new rule matches your expectations better.

one example:
image

The result of your code is not the same as in bvbeek's! Is nobody going to lean something at school anymore?

Was this page helpful?
0 / 5 - 0 ratings