如何避免很多其他条件 [英] How to avoid a lot of if else conditions

查看:107
本文介绍了如何避免很多其他条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多关于代码重构和避免if else语句的主题。
实际上,我有一个班级,我使用了很多if - else条件。

I have read a lot of topics about code refactoring and avoiding of if else statements. Actually, I have a class where I am using a lot of if - else conditions.

更多细节:我在每行使用pull解析器我的肥皂回复,我将检查是否有我感兴趣的标签,如果没有,检查另一个标签等:

More details: I am using the pull parser and on each line of my soap response, I will check if there is a tag I am interested on, if not, check another tag etc:

 if(eventType == XmlPullParser.START_TAG) {
            soapResponse= xpp.getName().toString();

            if (soapResponse.equals("EditorialOffice")){  
                eventType = xpp.next();
                if (xpp.getText()!=null){
                editorialOffice += xpp.getText();
                }
            }   
            else if (soapResponse.equals("EditorialBoard")){  
                eventType = xpp.next();
                if (xpp.getText()!=null){
                editorialBoard += xpp.getText();
                }
            }
            else if (soapResponse.equals("AdvisoryBoard")){  
                eventType = xpp.next();
                if (xpp.getText()!=null){
                advisoryBoard += xpp.getText();
                }
            }   
        }
        eventType = xpp.next();
     }

现在,我想使用somethimg else,而不是那些if else条件,但我不知道是什么。

Now, I would like to use somethimg else, instead of those if else conditions, but I don't know what.

你能给我一个例子或一个好的教程页吗?

Can you please give me an example or a good tutorial page?

谢谢。

推荐答案

在这种特殊情况下,由于除了String之外,所有3种情况的代码基本相同附加到,我将为每个正在构建的字符串创建一个映射条目:

In this particular case, since the code is essentially identical for all 3 case except for the String being appended to, I would have a map entry for each of the Strings being built:

Map<String,String> map = new HashMap<String,String>();
map.put("EditorialOffice","");
map.put("EditorialBoard","");
map.put("AdvisoryBoard","");
// could make constants for above Strings, or even an enum

然后更改你的代码如下

if(eventType == XmlPullParser.START_TAG) {
    soapResponse= xpp.getName().toString();
    String current = map.get(soapResponse);
    if (current != null) {
        eventType = xpp.next();
        if (xpp.getText()!=null){
            map.put( soapResponse, current += xpp.getText());
        }
    }
    eventType = xpp.next();
}

否if ... then ... else。甚至没有增加策略模式的多个类的复杂性等。地图是你的朋友。策略在某些情况下很棒,但这个很简单,可以在没有的情况下解决。

No "if... then... else". Not even the added complexity of multiple classes for strategy patterns, etc. Maps are your friend. Strategy is great in some situations, but this one is simple enough to be solved without.

这篇关于如何避免很多其他条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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