coderaider
coderaider

Reputation: 141

Multiple if conditions ,how to optimize it

i am working on a large application which has differnt conditions(ifs) and different methods associated with it.Please suggest a way to optimize below mentioned code(reduce as much of nested ifs as possible).I would like the code to able incorporate any other specific condition with ease.(I use property files to fetch conditions) .

 public getParameter(String parameter)
    {
      if(parameter=specific condition1
        ||parameter=specific condition2)
      {
      do this
      }
      if(parameter=specific condition3)
      {
       do something else
      }
      if(parameter=specific condition4)
      {
       do something else
      }
      if(parameter=general condition)
      {
       do something else
      }
      else  {
       do something else
      }

Upvotes: 1

Views: 2672

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382092

Say you have a property file with

do1=val1,val2,val3
do2=val5,val6,val7

(it seems you have a fixed set of actions)

You may load it with

    HashMap<String, HashSet<String>> rules = new HashMap<String, HashSet<String>>();
    for(String key : properties.stringPropertyNames()) {
        HashSet<String> set = new HashSet<String>();
        set.addAll(Arrays.asList(properties.getProperty(key).split(",")));
        rules.put(key, set);
    }

Now you have a map linking action names ("do1", etc.) to sets of possible values ("val1", etc.).

You may execute the rules with

    if (rules.get("do1").contains(parameter)) do1();
    if (rules.get("do2").contains(parameter)) do2();

(I let you add the necessary checks to avoid null pointer exceptions for example)

Upvotes: 2

hagensoft
hagensoft

Reputation: 1497

you could use a switch case.

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Upvotes: 0

Related Questions