Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for huge case statements

I'm trying to improve a Java project which uses a lot of large case statements. In cases where the case statement is used, it is used to handle an event which has an attribute associated to it. For example:

public void jumpOverWall(int wallID) {
    switch (wallID) {
            case 0:
            case 1213:
            case 2123:
            case 3123:
            case 4123:
    }
}

The numbers are non sequential and all require a different action to be performed - for example saying "You cannot jump over this wall" or moving the character to a set position. There are very few cases in which the case response follows a set pattern. What I mean by this is that the switch statements do not follow a pattern that would allow for code similar to:

public void jumpOverWall(int wallID) {
    someArray[1213] = 10;
    someArray[3123] = 20;

    if (playerJumpingSkill > someArray[wallID]) {
            // Do something
    } else {
            sendPlayerMessage("You cannot do this!");
    }
}

Therefore, I am wondering the best possible way of handling these 'events'. The whole idea of an 'event handler' style system is something that appeals to me but I am stuck as how to implement it (or a better solution to the problem). There are too many 'events' (in my opinion) to have a separate class for each one.

Is there a method / design for hooking events? Would this be applicable / work. I'd be looking to a method of easy hooking such as:

hookEvent(1213, new SomeInterface() {
    boolean eventOK() {
        // Do something
        return true;
    }
}

Then these 'hooks' would be checked for and called?

like image 747
jSherz Avatar asked Feb 21 '12 17:02

jSherz


1 Answers

Command pattern may be better option for you. Say, you have command object implementing interface:

public Interface Command {
      void processEvent(Event e);
}

Then you can have some hash of commands, keyed by event codes - much more readable. And you can even use DI container (spring is most popular, but there is also picocontainer or google guice, and surely I missed some) for command object creation - just register respective objects with keys as event codes. This will save you code for population of a hash.

And it even does not have to be a lot of clases - it could be just differently configured instances (depending on your use case) - no class exposion today

like image 120
Konstantin Pribluda Avatar answered Oct 04 '22 15:10

Konstantin Pribluda