Reputation: 2233
I'm still rather new to Java and trying to implement the best practices. I have a class that I would like to refactor heavily. I searched around and couldn't find anything that addresses my question in particular.
I have a class called Definitions
that maps all of the event names to their respective event ID. I have another class that parses out the events called EventHandler
. The EventHandler
has a switch statement that has grown very large. I'd like to reduce the size of the handler method so that the code is easier to read.
There is about 50 other events that I have truncated from below. In each case, there is about 20-30 lines of code. You can imagine how large this switch statement is.
My Definitions
class:
public class Definitions
{
public static class EVENT
{
public static final int SEQUENCE_START = 10;
public static final int SEQUENCE_HALT = 11;
public static final int SEQUENCE_AUTHORIZED = 12;
}
}
My EventHandler
class:
public handledStack parse(IRPEventType buffer)
{
final int eventId = Integer.parseInt(buffer.reader().parse("EventID"));
switch (eventId)
{
case Definitions.EVENT.SEQUENCE_START:
{
// stuff happens here
break;
}
case Definitions.EVENT.SEQUENCE_HALT:
{
// stuff happens here
break;
}
case Definitions.EVENT.SEQUENCE_AUTHORIZED:
{
// stuff happens here
break;
}
}
}
Upvotes: 0
Views: 840
Reputation: 744
I would prefer a stategy pattern implementation using enums. Check out Strategy pattern using Enums. Need a simple example in Java
interface Strategy {
void execute(Object param);
}
enum EVENT implements Strategy {
SEQUENCE_START(10) {
@Override
public void execute(Object param) {
// stuff happens here
}
},
SEQUENCE_HALT(11) {
@Override
public void execute(Object param) {
// stuff happens here
}
},
SEQUENCE_AUTHORIZED(12) {
@Override
public void execute (Object param){
// stuff happens here
}
};
private final int id;
EVENT(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
public class Test {
public void handledStack parse(IRPEventType buffer) {
final int eventId = Integer.parseInt(buffer.reader().parse("EventID"));
for (EVENT event : EVENT.values()) {
if (event.getId() == eventId) {
event.execute(param);
break;
}
}
}
}
Upvotes: 2