Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring if/else logic

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?

like image 712
David Avatar asked May 26 '10 13:05

David


People also ask

How do you refactor multiple if-else statements?

So, how do you refactor multiple nested if statements? The easiest possible way is to use guard clauses. A guard clause is an if statement that checks for a condition and favors early exit from the current method. If the condition is satisfied, the if block returns from the method.

Is if-else a code smell?

If-Else is often a code smell that can signal bad design decisions and the need for refactoring.


1 Answers

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.

like image 104
Péter Török Avatar answered Sep 22 '22 12:09

Péter Török