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

查看:37
本文介绍了如何删除大的 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 并查找并执行给定字符串的正确处理程序.

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 的元素可能会有所帮助 - 此处是一个例子.理想的解决方案是使用闭包/lambdas,但遗憾的是我们必须等到 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天全站免登陆