Design Patterns – Is It a Good Idea to Have Two Structs with the Same Members but Different Naming?

design

I am writing a program that involves working with both polar and Cartesian coordinates.

Does it make sense to create two different structs for each kind of points, one with X and Y members and one is with R and Theta members.

Or is it too much and it is better to have just one struct with first and second as members.

What I am writing is simple and it won't change much. But I am curious what is better from a design point of view.

I am thinking the first option is better. It seems more readable and I will get the benefit of type checking.

Best Answer

I have seen both solutions, so it is definitely context dependent.

For readability, having multiple structs as you suggest is very effective. However, in some environments, you want to do common manipulations to these structs, and you find yourself duplicating code, such as matrix*vector operations. It can get frustrating when the particular operation isn't available in your flavor of vector because nobody ported it there.

The extreme solution (which we eventually gave into) is to have a CRTP templated base class with functions get<0>() get<1>() and get<2>() to get the elements in a generic manner. Those functions are then defined in the Cartesian or Polar struct that derives from this base class. It solves all of the problems, but comes at a rather silly price: having to learn template metaprogramming. However, if template metaprogramming is already fair game for your project, it might be a good match.

Related Topic