Possible Duplicate:
What is the best way to replace or substitute if..else if..else trees in programs?
How can I avoid multiple if conditions? For example:
Public void search(String a,b,c,d,e)
String aTerm;
Now which of the single and multiple combinations of passed arguments contain "aTerm"? For example the output could be following:
1 - aTerm appears in "a" only
2 - aTerm appears in "a,c", and "e"
3 - aTerm appears in "d" and "e"
For each single or possible combination I want to call a specific function. I wrote so many if conditions but it looks bad. For example:
If(aTerm. equalsIgnoreCase(a)){ call function a();}
If(aTerm. equalsIgnoreCase(b)){ call function b();}
If(aTerm. equalsIgnoreCase(b) and aTerm. equalsIgnoreCase(b)){ call function ab();}
…………………… and so on………………………….
Is there any cleaner way to do it? Solution could be in PHP or Java.
Build a string and call the method by the string's name:
// Psuedo-code
str = "";
If( aTerm.equalsIgnoreCase(a)) str += "a";
If( aTerm.equalsIgnoreCase(b)) str += "b";
If( aTerm.equalsIgnoreCase(c)) str += "c";
If( aTerm.equalsIgnoreCase(d)) str += "d";
If( aTerm.equalsIgnoreCase(e)) str += "e";
call function named by str
Polymorphism can replace ifs/switch:
interface LogicWithMatcher {
boolean match(String aTerm);
void yourFunction();
}
class MatcherA implements LogicWithMatcher() {...}
class MatcherB implements LogicWithMatcher() {...}
class MatcherC implements LogicWithMatcher() {...}
class MatcherD implements LogicWithMatcher() {...}
class MatcherE implements LogicWithMatcher() {...}
If you have to match one function to a given input:
public LogicWithMatcher search(String yourString) {
LogicWithMatcher[] logics = {new MatcherA(), new MatcherB ...}
for (LogicWithMatcher logic : logics) {
if (logic.match(yourString))
return logic;
return null;
}
String yourString = "....."
LogicWithMatcher logic = search(yourString);
if (logic != null)
logic.yourFunction();
else
print("nothing matched");
Or if your given input may match multiple functions:
public void runFunctionsFor(String yourString) {
LogicWithMatcher[] logics = {new MatcherA(), new MatcherB ...}
for (LogicWithMatcher logic : logics) {
if (logic.match(yourString))
logic.yourFunction();
}
String yourString = "....."
runFunctionsFor(yourString);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With