I have a class that should read a message, extract its type from the envelope and then call a method that have to process the message; at each message type is associated an enum member.
There are 30+ message types.
One way to dispatch the message is to just use a switch, but it’s really ugly and error-prone (have I already tract that case? have I tract that case two times?).
One another way is to define an interface with a single method process(data) and create one class for each message type that implements that interface, register those classes with a map and, in the code that should process the message, just call map.get(messageType).process(data); but it’s really annoying to create 30+ classs.
One another way is to use reflection: define one function for each messagetype, with a precise signature and pattern name, like processMessagetype; then create a map from messagetype to Method (filled with a simple search upon getDeckaredMethods()) and then do something like: map.get(messageType).invoke(this,data).
What method you should use? What’s the overhead of using java’s reflection?
Reflection has a big overhead if you’re looking for good performance. If your routine (message dispatch) is going to be used over and over the polymorphism alternative is better. Also, IMO it’s better if looking in a OO perspective, since as stated by Brian on his answer, it’s easier and cheaper for maintenance.
Your clas handling 30+ messages can easily grow to 100+ messages, then you will have a class with 100+ methods, add the private methods too and code reuse will be hard and your class has just became a mess.
The overhead of reflection over polymorphism and switch is something like this:
I benchmarked these guys a while ago, and those were my results, I don’t have the code now because these benchmarks were done on my previous company and I don’t have access to that code anymore.