views:

59

answers:

2

Is it "better style" to send a message and hope the object responds, or to check to see if it responds to a selector and have some sort of fallback if it doesn't.

For example:

- (NSString *)stringForObjectValue:(id)obj {
    if ([obj respondsToSelector:@selector(intValue)]) {
        NSString *roman = [self formatRomanNumber:[obj intValue] resultSoFar:@""];
        return roman;
    } else {
        return [NSString stringWithFormat:@"can't format a %@", [obj class]];
    }
}

vs.

- (NSString *)stringForObjectValue:(id)obj {
    NSString *roman = format_roman(@"", [obj intValue]);
    return roman;
}

(the example is from a NSNumberFormatter subclass...but it could be from a NSObjectFormatter subclass...)

+1  A: 

If you don't know the exact type then using respondsToSelector: is definitely good style, because you risk an exception otherwise. And it's so important that there's a name for this technique: Duck Typing.

DarkDust
+2  A: 

If you're not 100% sure that all instances that come to your (stringForObjectValue) function respond to selector then you must perform that check to avoid crashes in runtime.

How to handle the cases when obj does not respond to intValue selector may depend on particular context where your method is used. For example you may return nil object from method in that case so you can easily see that something went wrong

Vladimir