R
Ryan Stewart
I'm trying to come up with a good method of unit conversion for use (currently)
in a cookbook application. Of course it would be preferable to make it as
portable as possible. For now, I'm looking to be able to convert between english
units of volume (tablespoons, cups, etc). A typical scenario would be something
like:
1) user inputs recipe containing 4 tablespoons of butter
2) user requests a tripled recipe, which would be 12 tablespoons of butter
That 12 tablespoons might be better represented as 3/4 cup.
I already have a Fraction class to handle the math. My question to you is how
would you implement the actual conversion mechanism? One way that springs to
mind would be to have a UnitOfVolume interface which is implemented by classes
such as Cup, TableSpoon, etc. The interface would specify methods like:
public TeaSpoon toTeaSpoons();
public TableSpoon toTableSpoons();
public Cup toCups();
public Quart toQuarts();
That seems klunky though, since every class would have every method, including
the one to convert to itself. Another alternative might be:
public UnitOfMeasure convertTo(String unit);
or
public UnitOfMeasure convertTo(Class unitClass);
But in either case, I think you'd have to store the relationships between every
unit somewhere.
How would you do it?
in a cookbook application. Of course it would be preferable to make it as
portable as possible. For now, I'm looking to be able to convert between english
units of volume (tablespoons, cups, etc). A typical scenario would be something
like:
1) user inputs recipe containing 4 tablespoons of butter
2) user requests a tripled recipe, which would be 12 tablespoons of butter
That 12 tablespoons might be better represented as 3/4 cup.
I already have a Fraction class to handle the math. My question to you is how
would you implement the actual conversion mechanism? One way that springs to
mind would be to have a UnitOfVolume interface which is implemented by classes
such as Cup, TableSpoon, etc. The interface would specify methods like:
public TeaSpoon toTeaSpoons();
public TableSpoon toTableSpoons();
public Cup toCups();
public Quart toQuarts();
That seems klunky though, since every class would have every method, including
the one to convert to itself. Another alternative might be:
public UnitOfMeasure convertTo(String unit);
or
public UnitOfMeasure convertTo(Class unitClass);
But in either case, I think you'd have to store the relationships between every
unit somewhere.
How would you do it?