在检查条件时,什么是最好的方式摆脱代码中的嵌套ifs? [英] What's the best way to get rid of nested ifs in code while checking for conditions?

查看:159
本文介绍了在检查条件时,什么是最好的方式摆脱代码中的嵌套ifs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Java开发一个BlackBerry应用程序,并且我有一个Options类,其中存储所有的用户设置。问题是我需要检查一些条件才能知道如何反应。随着我不断添加更多的功能,用户可以看到更多的GUI选项,更多的设置存储在Options类中,需要检查更多的条件。



以下代码例如:

  private void doCallMonitoring(int callId){
/ *这是我想要的部分避免。有
多个嵌套ifs。这里只是两个条件
,但是随着我添加更多,它将非常快速地获得不可维护的
* /
if(Options.isActive()。booleanValue()){
callTime =新的Timer();
TimerTask callTimeTask = new TimerTask(){
public void run(){
callTimeSeconds ++;
if((callTimeSeconds == Options.getSoftLimit()。intValue())&&(Phone.getActiveCall()。getStatus()== PhoneCall.STATUS_CONNECTED)){
injectDTMFTone(Phone。 getActiveCall());
} else if((callTimeSeconds> = Options.getHardLimit()。intValue())&((Phone.getActiveCall())getStatus()== PhoneCall.STATUS_CONNECTED)){
injectEndCall ();
}
}
};
callTime.schedule(callTimeTask,0,1000);
} else {
System.out.println(Service not active);
}
}

我想要的工作是验证所有选择一个单一的呼叫,从那里确定行动的诅咒。如何实现这样的设计?

解决方案

另一个选项是使诸如 injectDMTFTone() 检查是否要处理该条件,并根据是否被处理返回true或false。



例如:

  public void run(){
callTimeSeconds ++;
do {
if(handleInjectDMTONEone())
break;
if(handleInjectEndCall())
break;
} while(false);

callTime.schedule(callTimeTask,0,1000);


boolean handleInjectDMTFTone(){
if((callTimeSeconds!= Options.getSoftLimit()。intValue())||
(Phone.getActiveCall .getStatus()!= PhoneCall.STATUS_CONNECTED))
return false;

injectDTMFTone(Phone.getActiveCall());
返回true;
}

boolean handleInjectEndCall(){

if((callTimeSeconds< Options.getHardLimit()。intValue())||
.getActiveCall()。getStatus()!= PhoneCall.STATUS_CONNECTED))
return false;

injectEndCall();
返回true;
}

当然,而不是调用另一个 injectDMTONEone() 方法或 injectEndCall()方法,您只需在这些方法中内联逻辑。这样,您就可以将在同一个地方处理这些条件的所有逻辑分组。



这是我最喜欢的模式之一;使用如果语句接近方法的顶部是有意义的消除条件和返回。该方法的其余部分不是缩进许多级别,而且易于阅读。



您可以通过创建所有实现相同界面的对象来进一步扩展此方法,在一个处理程序的存储库中,您的运行方法可以迭代查看哪个处理它。这可能是也可能不会超过你的情况。


I'm developing a BlackBerry app in Java and I have an Options class where all user settings are stored. The problem is I need to check some conditions in order to know how to react. As I keep adding more features, more GUI options are shown to the user, more settings are stored in the Options class and more conditions need to be checked for.

Take the following code for example:

private void doCallMonitoring(int callId){
    /*This is the part that I want to avoid. Having
      multiple nested ifs. Here's just two conditions
      but as I add more, it will get unmantainable
      very quickly.*/
    if(Options.isActive().booleanValue()){
        callTime = new Timer();
        TimerTask callTimeTask = new TimerTask(){
            public void run(){
                callTimeSeconds++;
        if((callTimeSeconds == Options.getSoftLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectDTMFTone(Phone.getActiveCall());
        }else if((callTimeSeconds >= Options.getHardLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectEndCall();
                }
             }
        };     
        callTime.schedule(callTimeTask, 0,1000);
    }else{
    System.out.println("Service not active");
    }
}

How I would want it to work is to verify all options with a single call and from there determine the curse of action. How can I achieve such a design?

解决方案

Another option is to make methods such as injectDMTFTone() check to see if they want to handle that condition, and return true or false depending on if it was handled or not.

For instance:

public void run() {
    callTimeSeconds++;
    do {
        if (handleInjectDMTFTone())
            break;
        if (handleInjectEndCall())
            break;
    } while(false);

    callTime.schedule(callTimeTask, 0,1000);
}

boolean handleInjectDMTFTone() {
    if ((callTimeSeconds != Options.getSoftLimit().intValue()) ||
        (Phone.getActiveCall().getStatus() != PhoneCall.STATUS_CONNECTED))
        return false;

    injectDTMFTone(Phone.getActiveCall());
    return true;
}

boolean handleInjectEndCall() {

    if ((callTimeSeconds < Options.getHardLimit().intValue()) ||
        (Phone.getActiveCall().getStatus() != PhoneCall.STATUS_CONNECTED))
        return false;

    injectEndCall();
    return true;
}

Of course, instead of calling another injectDMTFTone() method or injectEndCall() method, you would just inline that logic right in those methods. In that way you've grouped all the logic of how and when to deal with those conditions in the same place.

This is one of my favorite patterns; use if statements as close to the top of methods as makes sense to eliminate conditions and return. The rest of the method is not indented many levels, and is easy and straightforward to read.

You can further extend this by creating objects that all implement the same interface and are in a repository of handlers that your run method can iterate over to see which will handle it. That may or may not be overkill to your case.

这篇关于在检查条件时,什么是最好的方式摆脱代码中的嵌套ifs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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