Is it better to allow the id type of the object or provide two arguments for two different types for the method?

Imagine a method adding an object to a specific NSMutableArray or NSMutableDictionary. Is it better (and why) to allow only one argument of type id or to allow two - one for the array and one for the dictionary?

For instance:

 - (void)addObjectToArray:(NSMutableArray *)anArray orDictionary:(NSMutableDictionary *)aDictionary; 

vs.

 - (void)addObjectToArrayOrDictionary:(id); 

If you use the first option, I just pass nil as a parameter depending on what I don't need (i.e. when added to the dictionary, I would pass nil as an array parameter).

+4
source share
1 answer

Neither one nor the other - I would apply two separate methods: one for the array and one for the dictionary:

 - (void)addObjectToArray:(NSMutableArray *)anArray; - (void)addObjectToDictionary:(NSMutableDictionary *)aDictionary; 

It is much simpler, more testable and more convenient than

  • A method with an inconvenient signature and fuzzy behavior depending on its arguments (for example, what happens when the arguments are equal to nil or both are not nil ?); or

  • A weakly typed method that accepts any random instance of Objective-C and must still check its type at runtime.

+9
source

All Articles