Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoid multiple if conditions [duplicate]

Tags:

java

php

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.

like image 865
user751637 Avatar asked Nov 03 '22 07:11

user751637


2 Answers

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
like image 66
Niet the Dark Absol Avatar answered Nov 11 '22 16:11

Niet the Dark Absol


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);
like image 20
Luigi R. Viggiano Avatar answered Nov 11 '22 16:11

Luigi R. Viggiano