• 4

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.

Yes, while both Cartesian and Polar are (in their place) eminently sensible coordinate representation schemes, they should ideally never be mixed (if you have a point Cartesian{1,1}, it is a very different point from Polar{1,1}).

Depending on your needs, it may also be worth implementing a Coordinate interface, with methods like X()Y()Displacement() and Angle() (or possibly Radius() and Theta(), depending on).

  • 0
Reply Report

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.

  • 3
Reply Report