Re: Elegant way to eliminate large conditional?
Re: Elegant way to eliminate large conditional?
- Subject: Re: Elegant way to eliminate large conditional?
- From: Drew McCormack <email@hidden>
- Date: Sat, 4 Jan 2003 09:27:35 +0100
On Saturday, January 4, 2003, at 04:50 AM, Andrew Merenbach wrote:
I'm developing a program that includes a unit converter which, among
other things, can convert from any one of five temperature scales to
any of the other five temperature scales. The code is hard to
maintain, unfortunately, as I use a rather long conditional (with
multiple sub-conditionals) to determine the "to" and "from" scales.
Is there some (elegant) way to use a matrix-like setup (a
two-dimensional selector or even an array?) that, given two arguments
(a range of five numbers, for each of the temperature scales) will
execute a different one of 25 equations or selectors?
Take care,
Andrew Merenbach
If I see a big ugly conditional, I immediately think OO. It is
interesting that nobody has suggested this. Perhaps it is a bit
overkill, because you will end up with 5 or 6 classes, but I think it
is the most robust solution.
I would have a "Temperature" class, and a abstract base class
"TemperatureRep" or "TemperatureUnit". The latter would have a couple
of abstract methods like
-(float)repValueForCeliusTemperature:(float)temp;
-(float)celciusTemperatureForRepValue:(float)temp;
Subclasses of TemperatureRep would represent your different units. Eg
CelciusTemperatureRep, KelvinTemperatureRep etc. These override the
methods, returning the correct values.
Your Temperature class would then store your temperature in Celcius,
but supply methods like this:
-(id)initWithValue:(float)temp andTemperatureRep:(TemperatureRep *)rep;
-(float)temperatureValueForTemperatureRep:(TemperatureRep *)rep;
Then write a class method for Temperature:
+(float)convertTemperatureValue:(float)val
fromTemperatureRep:(TemperatureRep *)rep1
toTemperatureRep:(TemperatureRep *)rep2 {
Temperature *temp =
[[[Temperature alloc] initWithValue:val andTemperatureRep:rep1]
autorelease]
return [temp temperatureValueForTemperatureRep:rep2];
}
Hope that was what you were looking for.
Drew
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
... ... ... ... ... ... ... ...
Dr. Drew McCormack
Trade Strategist (www.trade-strategist.com)
Trading simulation software for Mac OS X
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.