Element written twice in a row without being read
ID |
vbnet.correctness.no_unconditional_element_replace |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Dead Code |
Language |
VB.NET |
Description
Flags two consecutive statements that assign to the same element of the same collection with
nothing in between, written either with index syntax (Prices(sku) = …) or through the
Item property (cache.Item(sku) = …). Dictionaries and arrays are both matched. Writes
separated by any other statement, writes on mutually exclusive branches, a second write that
is guarded by a condition, and writes to different keys or different collections are all left
alone.
Rationale
Nothing can observe the first value, so that statement is dead and the work behind its right-hand side — a lookup, a computation, a service call — is wasted. The more serious reading is that the pair is not redundant at all but wrong: one of the two statements was meant to name a different key or a different collection, so the second write is destroying data the program still needs. Either way a value is silently lost, and because the surviving write looks perfectly plausible on its own, the loss is normally discovered only when the missing entry is chased back from somewhere else entirely.
The following code illustrates the pattern detected by this rule:
Public Sub Seed(ByVal sku As String)
' FLAGGED: Element written twice in a row without being read
Prices(sku) = 0D
Prices(sku) = 9.99D
End Sub
Remediation
Delete the write that is immediately overwritten, or correct the key or the collection on whichever of the two statements is wrong. Guard the second write when the first value has to survive in some cases.
' Before: the first value is discarded before anything can read it
Prices(sku) = 9.99D
Prices(sku) = 4.99D
' After
Prices(sku) = 9.99D
If promo Then
Prices(sku) = 4.99D
End If