mardi 29 mars 2022

Mapping a string "algorithmId" to a method call in Java

I've written some code using Java reflection (Method, Class.cast(Object) etc etc) that takes in a string "algorithmId" and uses that to dynamically determine which method to call next, and what type of response to expect.

The reason, in my mind, is to avoid something like this:

if (someInput.equals("A")) {doSomethingA(someData);}
if (someInput.equals("B")) {doSomethingB(someData);}
///.....
if (someInput.equals("Z")) {doSomethingZ(someData);}

My only question is, is this a worthwhile endeavor? Have I really gained anything by avoiding the if statements, and introducing the complexity of all this mapping? Is the code really "cleaner" if both approaches require a bit of thought for a maintainer to understand in either scenario?

The application isn't performance sensitive and to the end user, they're just sending their data to the same endpoint anyway.





Aucun commentaire:

Enregistrer un commentaire