StefanMaron / BusinessCentral.LinterCop

Community driven code linter for AL (MS Dynamics 365 Business Central)
https://stefanmaron.com
MIT License
77 stars 31 forks source link

LC0010: the cyclomatic complexity of CASE statements #566

Closed Pazzakara closed 3 months ago

Pazzakara commented 7 months ago

I really like the LC0010 (check Cyclomatic Complexity/Maintainability Index) because it always reminds me to write simple and short functions. But as soon as I have to make a distinction between enum values, I have to violate this rule. Example: an enum has 10 possible values. Depending on the option, something different should happen. The simplest/least complex way to program this is:

local procedure CheckOption(MyEnum: Enum "My Enum") begin case MyEnum of MyEnum::Value1: DoOption1(); MyEnum::Value2: DoOption2(); MyEnum::Value3: DoOption3(); ... MyEnum::Value10: DoOption10(); end; end;

but this function will raise a LC0010 anyway (cyclomatic complexity >= 8). But there is no posibility to do this less complex.

I would like to suggest that a case statement increases the cyclomatic complexity only by 1, no matter how many option values are queried. BTW: this is the only way to get an advantage from case statements compared to querying the options with 10 if-then statements.

If you think this change would contravene the definition of cyclomatic complexity too much, I would like to ask if my suggestion can be added as an optional setting, so that I can activate it via the extension settings.

Arthurvdv commented 6 months ago

I completely understand your request and also I've stumbled upon this to be honest. Applying a case statement with different enum values will indeed quite easily hit the cyclomatic complexity threshold of the LC0010 rule. I'm not on expert on the calculation of the cyclomatic complexity, where I'm unsure if changing the behavior of the rule is the right approach for resolving this.

Ideally we should replace a CASE statement with Enums and Interfaces to achieve extensibility and improve code maintainability.

Cognitive Complexity In the future maybe we can add Cognitive Complexity to the LinterCop as an alternative: https://github.com/StefanMaron/BusinessCentral.LinterCop/discussions/285. An example of the differences between the both of them:

image https://www.sonarsource.com/blog/cognitive-complexity-because-testability-understandability/