4

Imagine that a method is going to add an object to either a certain NSMutableArray or NSMutableDictionary. Is it better (and why) to allow just a single argument with type id, or allow two--one for the array and one for the dictionary?

For example:

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

vs.

- (void)addObjectToArrayOrDictionary:(id); 

If using the first option, I'd just pass nil as the parameter to whichever one I don't need (i.e. if adding to a dictionary, i'd pass nil as the array parameter).

2
  • Dictionary expects a key apart from the object to store, so how are you passing the key? Commented Oct 18, 2011 at 11:20
  • The key is constructed based on a couple different integer values that the object has as properties. Commented Oct 18, 2011 at 13:27

1 Answer 1

9

Neither — I'd implement two separate methods, one for the array and one for the dictionary:

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

It's much simpler, more testable and more maintainable than

  1. A method with an awkward signature, and unclear behavior depending on its arguments (e.g. what happens when the arguments are both nil or both not nil?); or

  2. A weakly-typed method that accepts any random Objective-C instance, and has to validate its type at runtime anyway.

Sign up to request clarification or add additional context in comments.

2 Comments

Of course, both methods presumably do very similar things, so they should both call through to another method that contains their shared implementation (if possible.) No sense in writing the code twice.
Thanks BoltClock and @JonathanGrynspan. I should be able to spend a bit of time re-factoring my code tonight, afterwhich I imagine I'll accept this answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.