I plan to define a class, that among its properties contains coordinates for an x/y grid. However, I'm unsure of the 'best' way to approach the design of this. It's a very simple issue, I just want to do it correctly and have a justification!
One solution would be to have to two properties, of type 'int
', one for x and one for y, within the object.
The other would be define a typedef struct of two ints containing x/y values and naming it <ClassPrefix>Coordinate
. Similar to CGSize
?
Are there any other/better ways to do this? Which is preferred? Not sure how to justify either way.
Thanks!
Tim.
The answer to the "Which one is preferred?" question depends on a few factors:
- How many items like this you plan to create? - If the answer is "millions",
struct
wins; if the answer is "fifty eight", object wins.
- Do you need to define methods on it? - If the answer is "yes", object wins; otherwise,
struct
may be OK.
- Do you plan to define arrays of it? - If the answer is "yes",
struct
may be a better choice.
- Do you need to create and destroy it often? - If the answer is "yes",
struct
may be a better choice.
Ultimately, your design constraints help you determine what's best; there is no data structure that is universally "better".
In addition to @dasblinkenlight answer, I'll give you some decision advices:
Is the structure immutable after creation?
Use an object.
Does the structure owns (= retains) pointers to other objects or arrays (both C arrays or NSArray
)? Does it interact with objects (= has methods with object parameters)?
Then use an object.
Does the structure contains only primitive types (int
, float
, other struct
s etc) and it interacts only with other primitives/structs?
Then use a struct
with functions.
It is a trade off.
A class and its instances will cost more in resource, especially when you have to make a lot of them. If there will not be so many instances, it is not a problem.
Structure is faster but it's difficult to extent and the most inconvenient thing is a struct can not hold objects or method.
For your example, if you just use it for coordinates, I suggest you to use struct. But it depends on your design and code. There is no absolute judgment which is best.