I have a java class with a thousand line method of if/else logic like this:
if (userType == \"admin\") {
if (age > 12) {
if (location == \"
You may use Chain of Responsibility pattern.
Refactor if-else
statements into classes with an interface IUserController
for instance.
Initialize your chain within a list or a tree or any suitable data structure, and execute desired functionality in this chain. You may use Builder pattern to create mentioned data structure. It resembles to strategy pattern but in chain of responsibility pattern, an instance in the chain can call linked instance(s).
Moreover, you can model location specific functionality by using strategy pattern. Hope it helps.
You should use Strategies, possibly implemented within an enum, e.g.:
enum UserType {
ADMIN() {
public void doStuff() {
// do stuff the Admin way
}
},
STUDENT {
public void doStuff() {
// do stuff the Student way
}
};
public abstract void doStuff();
}
As the code structure within each outermost if
branch in your code looks pretty much the same, in the next step of refactoring you might want to factor out that duplication using template methods. Alternatively, you might turn Location (and possibly Age) into a strategy as well.
Update: in Java4, you can implement a typesafe enum by hand, and use plain old subclassing to implement the different strategies.