NSNumber factory call instead of a boxed expression
ID |
objectivec.maintainability.use_boxed_expression |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Idiom |
Language |
Objective-C |
Description
Reports a call to one of the NSNumber numberWith…: factory methods, which the boxed expression syntax @(…) replaces. Occurrences inside a comment or a string literal are not reported. Only the class factory methods are matched; the [[NSNumber alloc] initWith…:] spelling is not reported.
Rationale
[NSNumber numberWithUnsignedLongLong:total] says twice what @(total) says once: the wrapper class, the exact C type of the value, and the value itself. Naming the C type by hand is the part that goes wrong - the compiler will happily narrow a long through numberWithInt:, and the truncation only shows up as a wrong number much later. The boxed form takes the type from the expression, so it cannot disagree with it.
The following code illustrates the pattern detected by this rule:
@implementation Boxing
- (void)factories:(NSInteger)count enabled:(BOOL)enabled {
// FLAGGED: NSNumber factory call instead of a boxed expression
NSNumber *total = [NSNumber numberWithInteger:count];
// FLAGGED: NSNumber factory call instead of a boxed expression
NSNumber *flag = [NSNumber numberWithBool:enabled];
// FLAGGED: NSNumber factory call instead of a boxed expression
NSNumber *ratio = [NSNumber numberWithDouble:count / 2.0];
// FLAGGED: NSNumber factory call instead of a boxed expression
NSNumber *wide = [NSNumber numberWithUnsignedLongLong:(unsigned long long)count];
// FLAGGED: NSNumber factory call instead of a boxed expression
NSNumber *parsed = [NSNumber numberWithInt:[@"5" intValue]];
NSLog(@"%@ %@ %@ %@ %@", total, flag, ratio, wide, parsed);
}
@end