Coding style: checking user input is messy. Am I doing it wrong?
Whenever I check user input it always gets really messy. An example of
this might be address input. You could have the following:
13B Main Street 13 B Main Street 13b, Main Street 13 B, Main Street
If I were coding this, it would end up like
String number,letter,street; //To be filled with "13","B","Main Street"
String address = getUserInput();
String[] tokens = address.split(" ");
if(tokens[0].isNumeric() == false){
//It could be 13B rather than 13
String number = "";
for(Character c: tokens[0].toCharArray()){
if(c.isDigit() == false){
//We could have found the apartment letter
if(number.isEmpty()){
//The address is invalid, throw error.
} else {
//Make sure it was a letter
if(c.isLetter()){
letter = c;
} else {
//throw error
}
}
} else {
number += c;
}
}
} else {
//...continue all other possibilities
}
Note that the above code is something I threw together quickly - some of
the methods don't exist and it won't compile.
My point is that it just looks messy. So many ifs inside ifs. When I look
at it I see something very unelegant. If I were to actually code to entire
thing, capable of taking addresses in those 4 formats, it would be scores
and scores of lines of code.
Is there a trick I'm missing here? Is there a way to make it any less ugly?
No comments:
Post a Comment