Same element assigned twice in a row
ID |
objectivec.correctness.no_unconditional_element_replace |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Dead Code |
Language |
Objective-C |
Description
Reports two consecutive statements, at the same indentation, that subscript the same collection with the same key and assign to it, where the second assignment does not read the element back. C arrays and the Objective-C subscripting operators on NSMutableArray and NSMutableDictionary are both matched. Writes separated by any other statement, writes to different keys or different collections, a second write guarded by a condition, writes on opposite branches, and a compound assignment such as += are all left alone.
Rationale
Nothing can observe the first value, so that statement is dead and whatever produced its right-hand side - a lookup, a computation, a network call - was work done for nothing. The more serious reading is that the pair is not redundant but wrong: one of the two lines 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 lost silently, and because the surviving write reads perfectly plausibly on its own, the loss is usually traced back from somewhere else entirely.
The following code illustrates the pattern detected by this rule:
@implementation Catalogue
- (void)priceItem:(NSString *)sku {
// FLAGGED: Same element assigned twice in a row
_prices[sku] = @(9.99);
_prices[sku] = @(4.99);
}
- (void)publish:(NSString *)sku { }
- (void)log:(NSString *)text { }
- (id)load:(NSString *)key { return nil; }
- (id)reload:(NSString *)key { return nil; }
- (id)baseValue { return nil; }
- (id)discountedValue { return nil; }
@end