If you don't want to track all the conversions from X to Y, you really only need one set. You could use a HashMap and just track one of the conversions (for example just the meters column).
It gets away with it by converting to meters (the multiplication) first and then to your desired unit (the division) second.
(Not a java dev, so if the syntax is off, take it with a grain of salt... I don't know if there's a "good" instance initializer for maps like there is in C#)
Take a step further. We may create a Distance class. In this way, all calculations can be handled inside and "distances" can be passed around without worrying about the unit.
Your syntax is indeed off, but it's a way better solution than the original.
With DistanceUnit being an Enum, i would actually go a step further and make the conversion to (or from, who cares) to meters a field in the Enum. No need to ever initialize a map; and you can even add all the logic in the Enum if you wish to do so. (Some will argue that breaks the single responsibility principle...)
You don't change the ordinal value of the Enum. In Java, Enums are just special classes. They can have fields and methods and constructors like any other class.
@Override
public double convertUnits(DistanceUnit unit1, DistanceUnit unit2, double input) { // A useful method
double out = 0.0;
switch (unit1) {
case MM:
switch (unit2) {
case MM: // mm to mm
out = input;
break;case CM: // mm to cm
out = input / 10;
break;case METER: // mm to m
out = input / 1000;
break;case INCH: // mm to in
out = input / 25.4;
break;
}
break;
case CM:
switch (unit2) {
case MM: // cm to mm
out = input * 10;
break;case CM: // cm to cm
out = input;
break;
case METER: // cm to m
out = input / 100;
break;case INCH: // cm to in
out = input / 2.54;
break;
}
break;
case METER:
switch (unit2) {
case MM: // m to mm
out = input * 1000;
break;case CM: // m to cm
out = input * 100;
break;
case METER: // m to m
out = input;
break;case INCH: // m to in
out = input * 39.37;
break;
}
break;
case INCH:
switch (unit2) {
case MM: // in to mm
out = input * 25.4;
break;case CM: // in to cm
out = input / 2.54;
break;
case METER: // in to m
out = input / 39.37;
break;case INCH: // in to in
out = input;
break;
}
break;
}
return out;
}
6
u/[deleted] Dec 11 '22
My refactor (with a few test cases):
18
u/TiozinNub Dec 11 '22
THE INDENTATION AAAA
8
u/DevXusYT Dec 12 '22
Two switch's nested? You need more functions.
4
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Dec 12 '22
Image Transcription: Code
I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!
2
u/N11FiRe Dec 12 '22
Why not just make different functions. Like convertM2MM?
2
u/[deleted] Dec 12 '22
The documentation is spot on, especially the end note on the signature.
Like... greatest of all docs.
1
u/[deleted] Dec 19 '22
Damn... And during this time, Java 17 switches supports
yieldand lambdas... Is sad ಥ﹏ಥ