I’m currently building a unit converter app in Java (as a beginner), and I want to avoid duplicating logic for each type of unit.
Right now, I have different enums like Length, Weight, Time, etc., and each enum constant has a conversion factor to a base unit (e.g. meters, kilograms, etc.). These enums all implement a common Units interface:
public interface Units {}
public enum Length implements Units {
METRE(1.0), KILOMETRE(1000), CENTIMETRE(0.01), ...;
private final double toMetreFactor;
Length(double factor) {
this.toMetreFactor = factor;
}
public double getToMetreFactor() {
return toMetreFactor;
}
}
In my ConverterModel class, I currently have methods like this:
public double convertLength(double value, Length input, Length output) {
double base = value * input.getToMetreFactor();
return base / output.getToMetreFactor();
}
But this means I need to write similar methods for every category (convertWeight, convertTime, etc.).
I’d like to generalize this logic so I can write one reusable method like:
public double convert(double value, Units from, Units to);
I already have my GUI set up with JComboBox, so I’m passing the selected units as Units. However, I can’t access the conversion factor unless I cast to the specific enum (e.g., Length), which feels clunky and not extensible.
Is it possible to design the Units interface (or the enums) so that I can call something like from.getToBaseFactor() without casting? Or can I somehow make the convert(...) method universal?