0

Is it redundant to check isKindOfClass even for non id variables in Objective C?

Teammate wrote Swift code. I am reviewing. Do I really need to check with isKindOfClass in the condition or its redundant?

-(void) checkCalorie:(NSMutableDictionary *) update {

    NSString *foodInfoId = [update objectForKey:FOOD_INFO_ID];
    double calorie = [[update objectForKey:CALORIE] doubleValue];
    if ([foodInfoId isKindOfClass:[NSString class]] && calorie < 0)
    {
        calorie = 0.0;
        // some logic
    }
}
Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256
  • Code review entry is deleted. Please unvote. @Roman – Sazzad Hissain Khan Aug 30 '20 at 14:03
  • 1
    "even for non id variables"? Why ? You know that `NSString *foodInfoId = [update objectForKey:FOOD_INFO_ID];`, there is nothing that confirms that `fooldInfoId` is really a `NSString` object, right? So, checking the class might be relevant. It really depends on your case. – Larme Sep 01 '20 at 10:23

1 Answers1

1

I think you should refactor this code with the dynamic_cast implemented for Objective-C. You can check this question for inspiration. For instance, use objc_dynamic_cast from this answer, and then you will have the following code:

-(void)checkCalorie:(NSMutableDictionary *)update {
    NSString *foodInfoId = objc_dynamic_cast([update objectForKey:FOOD_INFO_ID], NSString);
    double calorie = [[update objectForKey:CALORIE] doubleValue];
    if (foodInfoId != nil && calorie < 0) {
        calorie = 0.0;
        // some logic
    }
}
Roman Podymov
  • 4,168
  • 4
  • 30
  • 57