5

Our legacy code has a long code of if else blocks that depend on events and object type

if(event == A && objectType == O1){
.....
}
else if (event == A && objectType == O2){
 ....
}
else if (....)
....
....

With more and more conditions introducing, I was thinking of replacing this logic with Command pattern for each condition. But the number of classes required would be (no. of events) * (no. of object types). Is there any simpler way to refactor this code?

sidgate
  • 14,650
  • 11
  • 68
  • 119
  • 1
    cant think of any directly, however you can always write some macros in your IDE or editor... worth doing in any case, you code using the command pattern will be much clearer. – vikingsteve Jun 14 '13 at 11:32
  • 1
    If contents of conditional block are completely different, then no. If they share some kind of common logic depending on `event` and/or `objectType`, then yes. – Mehmet Ataş Jun 14 '13 at 11:32
  • 3
    http://stackoverflow.com/questions/2913495/refactoring-if-else-logic read this – lakshman Jun 14 '13 at 11:34

2 Answers2

6

Create a class enclosing event and objectType, make it implement .equals() and .hashCode(). Create a generic class for each execution block too.

Then you'll be able to use a Map and a simple lookup will return what is needed to execute.

fge
  • 119,121
  • 33
  • 254
  • 329
3

The pattern you may be looking for is often called double dispatching or sometimes Visitor pattern. http://en.wikipedia.org/wiki/Visitor_pattern

Create a set of classes for events and a set for object types. Create an interface

public interface VisitEvent {
    public void visit(EventA eventA);
    public void visit(EventB eventB);
    // for each event class
}

Within the event class, you have to invoke the visit pattern on the object type class.

public class EventA {
    public void visit(ObjectTypeParent otp) {
        otp.visit(this);
    }
}

Presuming that the object type classes inherit from a common class

public abstract class ObjectTypeParent implements VisitEvent {
    public void visit(EventA eventA) {
        // default code here
    }
    // same for each event visit from VisitEvent
}

then

public class ObjectType01 extends ObjectTypeParent {
    public void visit(EventA eventA) {
       // stuff you want done for this combination
    }
    // don't implement the ones that have common behavior
}
Bob Dalgleish
  • 8,167
  • 4
  • 32
  • 42