Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef struct vs. Object - Benefits

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.

like image 465
Tim Avatar asked Mar 12 '13 10:03

Tim


People also ask

What is the advantage of using typedef?

Typedefs provide a level of abstraction away from the actual types being used, allowing you, the programmer, to focus more on the concept of just what a variable should mean. This makes it easier to write clean code, but it also makes it far easier to modify your code.

Should I use typedef struct?

The use of typedef most often serves no purpose but to obfuscate the data structure usage. Since only { struct (6), enum (4), union (5) } number of keystrokes are used to declare a data type there is almost no use for the aliasing of the struct.

What is difference between typedef and struct?

In C++, there is no difference between 'struct' and 'typedef struct' because, in C++, all struct/union/enum/class declarations act like they are implicitly typedef'ed, as long as the name is not hidden by another declaration with the same name.

Is typedef good practice?

Best PracticesUse a typedef for each new type created in the code made from a template. Give the typedef a meaningful, succinct name. Sometimes, typedefs should also be created for simple types. Again, a uniquely identifiable, meaningful name for a type increases maintainablity and readability.


1 Answers

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".

like image 100
Sergey Kalinichenko Avatar answered Oct 06 '22 19:10

Sergey Kalinichenko