Rubberduck icon indicating copy to clipboard operation
Rubberduck copied to clipboard

Object reference could be held by With block

Open retailcoder opened this issue 8 years ago • 2 comments

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 With block variable declared in the procedure where the With block is; we can't do this with a parameter or a module-level variable - it has to be a local.
  • The With block variable is assigned once, before the With block. 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 the With block.
  • The With block variable is only ever referenced within the With block. If it's used outside of it, we can't proceed. Or perhaps in that case we could suggest moving it inside the With block?
  • Quick-fix removes both the declaration and the assignment, and modifies the With block 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.

retailcoder avatar Mar 09 '17 02:03 retailcoder