I'm creating a hex, decimal and binary converter and it's going well so far. This is my second project on the iPhone and I'm a beginner. However, I was wondering how can I simplify what I have (a bunch of if statements). I have:
if (entered is hex)
if (binary button clicked)
convert to binary
if (decimal button clicked)
convert to decimal
else (hex button clicked)
keep in hex and inform
else if (entered is binary)
if (hex button clicked)
convert to hex
if (decimal button clicked)
convert to decimal
else (binary button clicked)
keep in binary and inform user
else if (entered is decimal)
if (hex button clicked)
convert to binary
if (binary button clicked)
convert to hex
else (decimal button clicked)
keep in decimal and inform user
else
give error if something else entered in
This looks quite repetitive to me. All these are in one class, all of these if statement are very similar to one another, and so I was wondering if there is something I could do?
Thanks for your time.
I would always store the entered value (internally) in the same format (let's use hex for this example). Then, you can use something like this, which is much more streamlined:
// Convert the user entered value to hex
if (enteredValue is hex)
internalHexValue = enteredValue
else if (entered is binary)
internalHexValue = convert enteredValue (binary) to hex
else if (entered is decimal)
internalHexValue = convert enteredValue (decimal) to hex
else
error and return
// Now, you have far less repetition because you only have to convert from hex:
if (binary button clicked)
convertedValue = convert internalHexValue to binary
else if (decimal button clicked)
convertedValue = convert internalHexValue to decimal
else (hex button clicked)
convertedValue = internalHexValue
// Lastly, see if they selected the same format for input and output:
if (enteredValue == convertedValue)
inform user
You could also break the example above into multiple methods in order to make it easier to read by writing it like this (error checking removed for clarity):
internalHexValue = [self convertEnteredValueToHex:enteredValue];
convertedValue = [self convertHexValueToUserSelectedFormat:internalHexValue];
if (enteredValue == convertedValue)
inform user
I would also make all of the "convert XXX to XXX" lines different methods within your class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With