Variable name is one or two characters long
ID |
objectivec.maintainability.naming_single_char_var |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Naming |
Language |
Objective-C |
Description
Reports the declaration of a variable whose name is one or two characters long, such as NSInteger t = 0; or id d;. Only standalone declarations are reported: a counter declared in a for header is part of the loop and is left alone, and so are message-send arguments and method parameters.
Rationale
A one or two character name says nothing about what the variable holds, so every reader has to scroll back to the declaration and reconstruct the meaning from the initialiser - and a reader who guesses wrong writes a bug. The names are also unsearchable: grepping for t in a source tree returns every line, so a rename or an impact analysis cannot be done mechanically. Short names outlive the ten-line method they were introduced in, and they are exactly the names that make a long method hard to break up later.
The following code illustrates the pattern detected by this rule:
@implementation Cart
- (NSInteger)totalForItems:(NSArray<NSNumber *> *)items rate:(double)rate {
NSInteger t = 0;
id d;
// FLAGGED: Variable name is one or two characters long
NSString *ab = @"two";
// FLAGGED: Variable name is one or two characters long
const double vr = rate;
NSInteger runningTotal = 0;
NSString *label = @"cart";
NSMutableArray<NSNumber *> *accumulated = [NSMutableArray array];
// A loop counter is part of the `for` header, not a standalone declaration, so it is not
// reported.
for (NSUInteger i = 0; i < items.count; i++) {
runningTotal += items[i].integerValue;
}
// NSInteger t = 0;
NSLog(@"NSInteger t = 0;");
runningTotal = 1;
self.name = label;
NSLog(@"%@ %@ %ld %@ %f", d, ab, (long)t, accumulated, vr);
return runningTotal;
}
@end
Remediation
Rename the variable after the thing it holds - runningTotal, discountRate, selectedAccount. Objective-C favours long descriptive names and the compiler charges nothing for them. Where a name genuinely has no meaning beyond "the loop index", declare it in the for header where its scope makes that clear.