如何删除大的if-else-if链 [英] How to remove large if-else-if chain

查看:109
本文介绍了如何删除大的if-else-if链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Java中if语句的长列表

我的任务是处理一些代码,并且有一个巨大的if-else-if链(100+ else-ifs)检查字符串。

I was tasked to work with some code, and there is a giant if-else-if chain (100+ else-ifs) that checks Strings.

什么是更新此代码的好技术,可以将if-else-if链缩小到更易于管理的位置。

What are some good techniques to update this code as to where the if-else-if chain can be shrunken down to something much more manageable.

链看起来像这样:

if(name.equals("abc")){
    do something
} else if(name.equals("xyz")){
    do something different
} else if(name.equals("mno")){
    do something different
} ......
.....
else{ 
   error
}


推荐答案

您可以将每个分支中的代码提取到单独的方法,然后将方法转换为公共基接口的实现(让我们称之为 Handler )。之后,您可以填写 Map< String,Handler> ,然后查找并执行给定字符串的正确处理程序。

You can extract the code in each branch to a separate method, then turn the methods into implementations of a common base interface (let's call it Handler). After that, you can fill a Map<String, Handler> and just look up and execute the right handler for given string.

不幸的是,为接口实现100多个子类需要相当多的样板代码,但目前在Java中没有更简单的方法来实现这一点。将案例实现为 Enum 的元素可能有所帮助 - 这是一个例子。理想的解决方案是使用闭包/ lambda,但是我们必须等到Java 8 ...

Unfortunately the implementation of 100+ subclasses for the interface requires quite a lot of boilerplate code, but currently there is no simpler way in Java to achieve this. Implementing the cases as elements of an Enum may help somewhat - here is an example. The ideal solution would be using closures / lambdas, but alas we have to wait till Java 8 for that...

这篇关于如何删除大的if-else-if链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆