重构一个长 servlet 条件

发布于 2024-11-29 08:02:46 字数 402 浏览 0 评论 0原文

我有一个 servlet,它可以接受多达两打不同类型的请求(在 servlet 中称为命令)。创建了一个非常大的条件来为这些请求提供服务,其结构如下:

if (command.equals("Command1"))
    doSomething();
else if (command.equals("Command2))
    doSomethingElse();
else if (command.equals("Command3))
    doThisOtherThing();
 ......

是否有更好的方法来编写此代码?我正在阅读一本关于 JUnit 测试的书,其中建议在条件上使用多态性,但我只是不知道如何在这个示例中执行此操作。有人有更好的主意吗?

谢谢你,

埃利奥特

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,

Elliott

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海螺姑娘 2024-12-06 08:02:46

鉴于您正在使用 Servlet,您正在寻找的是 FrontController。基本思想很简单,您拥有的每个命令字符串都可能被映射到一个 Map 中,并且您会将操作移交给这些命令。

一个非常简单的实现可能如下所示:

Command commandAction = this.commands.get( command );
commandAction.doAction( request, response );

这消除了对 if/switch 的需要,并且您可以将每个命令作为一个特定的类,从而改进您的代码组织。

显然,这是重新发明轮子,因为 Java 中的所有 Web MVC 框架(如 Struts、SpringMVC、VRaptor 和 Play)都实现了这种模式,并免费为您提供此功能,因此您也可以考虑切换到框架,而不是继续使用纯 servlet并构建您自己的本土 Web 框架。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文