tags:

views:

233

answers:

2

I noticed by looking at sample code from Apple, that they tend to design methods that receive structures instead of multiple parameters. Why is that? As far as ease of use, I personally prefer the latter, but as far as performance goes, is there one better choice than the other?

[pencil drawPoint:Point3Make(20,40,60)]
[pencil drawPointAtX:20 Y:50 Z:60]
+1  A: 

If you are passing the same set of parameters around it is useful to pass them in a structure because they belong together semantically.

The performance hit is probably negligible for such a simple structure as 3 points. Use the readable/reusable solution and then profile your code if you think it is slow :)

grepsedawk
So you mean structures have, in theory, better performance?
Steph Thirion
No, I mean they have performance similar to the solution without the structure in simple cases. You need to measure/profile your code to see if it really is a performance problem.
grepsedawk
+4  A: 

Don't muddle this question with concerns of performance. Don't make premature optimizations (until you know you have a problem) and when thinking about performance hot spots in your code, its almost always in areas dealing with I/O (eg, database, files). So, separate your question on message passing style with performance. You want to make the best design decision first, then optimize for performance only if needed.

With that being said, Apple does not recommend or prefer passing multiple parameters vs a structure/object. Generalizing this outside of the scope of Objective-C, use individuals parameters or objects when it makes sense in the particular scenario. In other words, there isn't a black and white answer that you can follow. Instead, use the following guidelines when deciding:

  • Pass objects/structures when it makes sense for the method to understand many/all members of the object
  • Pass objects/structures when you want to validate some rules on the relationship between the various members of the object. This allows you to ensure the consumer of your method constructs a valid object prior to calling your method (thus eliminating the need of the method to validate these conditions).
  • Pass individual arguments when it is clear the method makes sense and only needs certain elements rather than the entire object

Using a variation on your example, a paint method that takes two coordinates (X and Y) would benefit from taking a Point object rather than two variables, X and Y.

A method retrieveOrderByIdAndName would best be designed by taking the single id and name parameter rather than some container object.

Now, if there was some method to retrieve orders by many different criterion, it would make more send to create a retrieveOrderByCriteria and pass it some criteria structure.

shek