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:
Of course, instead of calling another
injectDMTFTone()method orinjectEndCall()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
ifstatements 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
runmethod can iterate over to see which will handle it. That may or may not be overkill to your case.