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?
Why not have a separate method for each case? That way, it makes your code more readable.