Rubberduck icon indicating copy to clipboard operation
Rubberduck copied to clipboard

Inspection for using logical operator Or in a Select Case

Open Energeer opened this issue 1 year ago • 3 comments

What Inspection for using logical operator Or in a Select Case.

Why The user may not realise that the Select Case may not follow the path they expect.

Example This code should trigger the inspection:

Public Function IsOdd(ByVal Number as Long) As Boolean
    Select Case Number
        Case 1 Or 3: 'here
            IsOdd = True
    End Select
End Function
Debug.Print IsOdd(1) 'False

QuickFixes

  1. Replace Or operator with Comma separator

    Example code, after quickfix is applied:

Public Function IsOdd(ByVal Number as Long) As Boolean
    Select Case Number
        Case 1, 3: 'here
            IsOdd = True
    End Select
End Function
Debug.Print IsOdd(1) 'True

Resources I don't know enough about the workings of the Select Case to suggest the right terminology for the resource strings.

Energeer avatar Nov 30 '22 09:11 Energeer

Problem is, logical operators would be used for jumping to a True case in a Select Case True block, so I don't think warning about them is necessarily warranted.

These operators used in any context with non-Boolean operands (this needs expression evaluation) are bitwise operators - there could be a hint-level inspection for that, but implementing it is tricky.

retailcoder avatar Nov 30 '22 13:11 retailcoder

Yes you're right. I decided to post this as I came across a bug in one of my projects, the source of which took me ages to find.. all due to using Enums and Select Cases and not fully understanding the knowledge contained in your second paragraph - so thanks for that! To someone wiser than me its going to be intentional usage and I can appreciate its really hard to determine the coders intent.

Trying to think of a way that you could reasonably inspect for the above: can you think of an example where a user would ever want/need to evaluate an expression of constants at runtime? Ie. Case 1 Or 3 is always going to evaluate to Case 3.. right? Perhaps a "pointless evaluation" inspection? :)

Energeer avatar Dec 08 '22 23:12 Energeer

There's one for unreachable case, although it won't pick up all positives but does enough to be helpful I think. We need RD to be able to evaluate expressions (and their resulting data type) in order to unlock all the "expression is always false" kind of goodies. It'll come, but v3.0 will probably come first 😉

retailcoder avatar Dec 08 '22 23:12 retailcoder