Member
Adam Gent
1 Posts
I have a java class with a thousand line method of if/else logic like this:
if (userType == "admin") {
if (age > 12) {
if (location == "USA") {
// do stuff
} else if (location == "Mexico") {
// do something slightly different than the US case
}
} else if (age < 12 && age > 4) {
if (location == "USA") {
// do something slightly different than the age > 12 US case
} else if (location == "Mexico") {
// do something slightly different
}
}
} else if (userType == "student") {
if (age > 12) {
if (location == "USA") {
// do stuff
} else if (location == "Mexico") {
// do something slightly different than the US case
}
} else if (age < 12 && age > 4) {
if (location == "USA") {
// do something slightly different than the age > 12 US case
} else if (location == "Mexico") {
// do something slightly different
}
}
How should I refactor this into something more managable?
Member
martin
2 Posts
I'm not a Java developer, but I'm guessing finding logical breaks in the if/else statements that can be encapsulated into their own methods, or even their own classes.
Member
Stephen Dryden
1 Posts
I'm also not a Java developer but is there not some sort of switch case statement which might make it more manageable. For example in c# it's something like this...
switch (values to be tested)
{
case (value outcome 1):
//do something
case (value outcome2);
//do something
}