Refactoring a long servlet conditional
I have a servlet which can accept upwards of two dozen different kinds of requests (called commands in the servlet). A very large conditional was created to service to these requests structured like this:
if (command.equals("Command1"))
doSomething();
else if (command.equals("Command2))
doSomethingElse();
else if (command.equals("Command3))
doThisOtherThing();
......
Is there a better way to write this code? I'm reading a book on JUnit testing that suggests using polymorphism over conditionals but I just don't see how to do this in this example. Does anyone have a better idea?
Thank you,
Ell开发者_开发问答iott
Given that you're using Servlets, what you're looking for is a FrontController. The basic idea is simple, each of those command Strings you have would possibly be mapped into a Map of and you would hand over the actions to these commands.
A really simple implementation could look like this:
Command commandAction = this.commands.get( command );
commandAction.doAction( request, response );
This removes the need of having an if/switch and you can have each command being a specific class, improving your code organization.
Obviously, this is reinventing the wheel as all web MVC frameworks in Java like Struts, SpringMVC, VRaptor and Play implement this pattern and give this functionality for free to you, so you could also think about switching to a framework instead of staying with pure servlets and building your own homegrown web framework.
精彩评论