Well, it's not good to use instanceof, but if you can't change the Event Interface even to add a "int getType()" or similar, at least you could restructure your code:
Use "else if" structure instead of just if structure. I would recommend putting the Event Types that are deeper inherited first, and consider the more general event declarations last (if you test event instanceof Event you will always become true).
This way at least you reduce complexity.
Assuming all your events directly implement Event Interface and there aren't other inheritance issues to check:
public int getEventCode(Event event) {
int result = event.getClass().hashCode() + 10;
if (event instanceof OneEvent) {
result = 1;
}
else if (event instanceof TwoEvent) {
result = 2;
}
else if (event instanceof ThreeEvent) {
result = 3;
}
else if (event instanceof FourEvent) {
result = 4;
}
else if (event instanceof FiveEvent) {
result = 5;
}
else if (event instanceof SixEvent) {
result = 6;
}
else if (event instanceof SevenEvent) {
result = 7;
}
else if (event instanceof EightEvent) {
result = 8;
}
else if (event instanceof NineEvent) {
result = 9;
}
else if (event instanceof TenEvent) {
result = 10;
}
return result;
}
I also changed your method so it will only declare one return variable, this is normally considered as a better coding practice as it also helps to reduce complexity, even though it has no real technical benefit in this particular case.
But as I said, if TenEvent extends FiveEvent you can also have issues. In that case I would recommend to use the Class of the event instance you receive, something like this:
public int getEventCode(Event event) {
int result = event.getClass().hashCode() + 10;
String eventClass = event.getClass().getSimpleName();
if ("OneEvent".equals(eventClass) {
result = 1;
}
else if ("TwoEvent".equals(eventClass)) {
result = 2;
}
return result;
}
I got lazy and am only writing the first two in the sample so you get the idea...
Or even nicer:
public int getEventCode(Event event) {
int result = event.getClass().hashCode() + 10;
Class eventClass = event.getClass();
if (OneEvent.class.equals(eventClass) {
result = 1;
}
else if (TwoEvent.class.equals(eventClass)) {
result = 2;
}
return result;
}