Rubberduck
Rubberduck copied to clipboard
Signature mismatch inspection
Sometimes an event handler signature can be typed manually:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
Cancel = True
Hide
End If
End Sub
At a glance, everything looks right - both the VBA compiler and the runtime won't complain: the signature matches the expected signature... as far as VBA signature matching rules are concerned. After all, the UserForm_QueryClose signature has two Integer parameters, right?
The problem is that at run-time, the above code would assign -1 (True) to the CloseMode parameter, and verify that the Cancel parameter is 0 (False) - and because the close mode will be 0 / vbFormControlMenu when the "red X" button is clicked, when stepping through the procedure looks like it's working as it should - the actual signature for the event has the parameters in a different order:
Private Sub UserForm_QueryClose(CloseMode As Integer, Cancel As Integer)
If CloseMode = vbFormControlMenu Then
Cancel = True
Hide
End If
End Sub
And this means a serious bug at run-time. When handlers are written by hand, it's easy to do it wrong, and the compiler or runtime won't give any clue, other than throwing puzzling automation errors when code later tries to access the unexpectedly destroyed object.
Let's implement an inspection that reports mismatching interface/event handler signatures using not only the types and number of parameters, but also their names... and since mismatching parameter types and number is already a compile error, let's just fire up an inspection result when it's the names that mismatch:
Mismatching signature A procedure looks like it's implementing an interface member or handling an event, but its signature doesn't match with that of the interface or member. While the code compiles and runs, this can introduce unexpected behavior at run-time.