Should I write one method to convert distances or a bunch of methods?
c++, switch-statement
Solution
Break it up into functions. What you have there is going to be very difficult to maintain and to use. It would be more convenient to the user and the programmer to have functions with descriptive names like:
double inchesToCentimeters(double inches);
double centimetersToInches(double cent);
The function names tell you exactly what function to call, and there's no need to pass in the extra parameter that keeps track of the units.
Just as an aside, in order to prevent having to keep track of what units a measurement is in, it's a good practice to always store you numbers in a common unit everywhere in your program, then convert to the display units only when you need to. For example, a program I'm maintaining now keeps all distance values in meters, but can convert to just about any distance unit you could think of.
When you use a common unit, you save yourself a lot of function writing. Say your common distance unit is meters, now once you write the functions converting from meters to every other unit you need, and from all the other units to meters, you can combine these to go from any unit - to meters - to any other unit.
Problem
I'm just learning C++ and programming. I'm creating a class called `Distance`. I want to allow the user (programmer using), my class the ability to convert distances from one unit of measure to another. For example: inches -> centimeters, miles -> kilometers, etc... My problem is that I want to have one method called `ConvertTo` that will convert to any unit of measure. Here's what I have so far: ``` // unit_of_measure is an enum containg all my supported lengths, // (eg. inches, centimeters, etc...) int Distance::ConvertTo(unit_of_measure convert_unit) { switch (convert_unit) { case inches: if (unit != inches) { if (unit == centimeters) { distance *= CM_TO_IN; unit = inches; return 0; } else { cerr << "Conversion not possible (yet)." << endl; return 1; } } else { cout << "Warning: Trying to convert inches to inches." << endl; return 2; } case centimeters: if (unit != centimeters) { if (unit == inches) { distance /= CM_TO_IN; unit = centimeters; return 0; } else { cerr << "Conversion not possible (yet)." << endl; return 1; } } else { cout << "Warning: Trying to convert inches to inches." << endl; return 2; } // I haven't written anything past here yet because it seems // like a bad idea to keep going with this huge switch // statement. default: cerr << "Undefined conversion unit." << endl; return -1; } } ``` So what do I do? Should I break this up or just continue on with what will become a HUGE switch statement.