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.