Rubberduck
Rubberduck copied to clipboard
Object reference could be held by With block
A language opportunity inspection:
Dim something As Object
Set something = New Object
With something
.Foo = 42
Debug.Print .Bar
End With
If a local variable is only ever used as a With variable and inside that With block, and only ever assigned once, then the object reference could be owned by the With block, and the snippet can be written as a With New block:
With New Object
.Foo = 42
Debug.Print .Bar
End With
So formally:
- A
Withblock variable declared in the procedure where theWithblock is; we can't do this with a parameter or a module-level variable - it has to be a local. - The
Withblock variable is assigned once, before theWithblock. There's a trap here that warrants tagging this issue with [code-path-analysis]: an assignment might be found inside an unreachable conditional block located above theWithblock. - The
Withblock variable is only ever referenced within theWithblock. If it's used outside of it, we can't proceed. Or perhaps in that case we could suggest moving it inside theWithblock? - Quick-fix removes both the declaration and the assignment, and modifies the
Withblock so that it includes the assignment's RHS expression.
Object reference could be held by With block. A local object variable is declared and assigned, but only used as a With block variable; if the With block held the object reference, no variable/assignment would be needed.