Let’s say we have two ifs that depend on each other:
if var exists {
if var is array {
//Do stuff with var
} else {
//Resolve the problem
}
} else {
//Resolve the problem in the exact same way as above
}
//Continue execution with the assumption that var is in the appropriate state
How can I refactor this to remove the duplicated code without using gotos or functions/methods?
9
Am I missing something more complicated here, or shouldn’t this just be:
if var exists and var is array {
//Do stuff with var
} else {
//Resolve the problem
}
//Continue execution with the assumption that var is in the appropriate state
The check for if var exists
will short-circuit and fall through to the else resolution block if it evaluates to false.
3
If you don’t mind “do stuff with var” runs every time:
if var does not exist {
//Resolve the problem
}
if var is array {
//Do stuff with var
}
//Continue execution with the assumption that var is in the appropriate state
If you don’t want “do stuff with var” to run every time (as in original code):
if var does not exist {
//Resolve the problem
flag = true
}
if var is array && flag == true {
//Do stuff with var
}
//Continue execution with the assumption that var is in the appropriate state
4
Assuming the tests cannot be joined in one expression I would write:
bool ok = false;
if var exists {
if var is array {
//Do stuff with var
ok = true;
}
}
if (!ok) {
//Resolve the problem
}
//Continue execution with the assumption that var is in the appropriate state
1