string - using switch block in java instead of multiple if statements -
public class { public void search(boolean[] searchlist) { // searchlist array used identify options search in given order // e.g. boolean [] searchlist = new boolean [] {false, false, true, false}; boolean searchl = false; boolean searchm = false; boolean searchk = false; boolean searcha = false; if(searchlist[0] == true) searchl = true; if(searchlist[1] == true) searchm = true; if(searchlist[2] == true) searchk = true; if(searchlist[3] == true) searcha = true; if(searchl == true) // write query search ls if(searchm == true) // write query search ms ........... }
is there way can simplify code ?
@all : sorry posting wrong question before. confused!
thanks, sony
public class { public enum searchoption { search_l, search_m, search_a, search_k; } /** * make them pass in enum search. * pros: type safe, can use selections give * cons: must add enum add new types * @param option */ public void enumsearch(searchoption option) { switch(option) { case search_a: system.out.println("i searching a"); break; case search_k: system.out.println("i searching k"); break; case search_l: system.out.println("i searching l"); break; case search_m: system.out.println("i searching m"); break; } } /** * use primitive input * pros: gives more options without updating enum * cons: users enter input don't want them use * @param option */ public void charsearch(char option) { switch(option) { case 'a': case 'a': system.out.println("i searching a"); break; case 'k': case 'k': system.out.println("i searching k"); break; case 'l': case 'l': system.out.println("i searching l"); break; case 'm': case 'm': system.out.println("i searching m"); break; } } /** * use primitive , don't check it! run it! * @param option */ public void uncheckedsearch(char option) { system.out.println("i searching " + option); } }
as per comment, here's updated example of method - make sure comment @ top updated!
/** * perform search based on options provided * list should in order of l, m, a, k * @note update comment more search options added * @param searchlist list of flags indicating search */ public void search(boolean[] searchlist) { // per docs, [0] denotes l search: if(searchlist[0]) // write query search ls // per docs, [1] denotes m search: if(searchlist[1]) // write query search ms // per docs, [2] denotes search: if(searchlist[2]) // write query search // per docs, [3] denotes k search: if(searchlist[3]) // write query search ks }
latest idea:
// use searchoption enum above map<searchoption, string> searches = new hashmap<searchoption, string>(); public list<searchresult> search(list<searchoption> options) { list<searchresult> results = new linkedlist<searchresult>(); for(searchoption option : options) { string query = searches.get(option); searchresult result = mysearchservice.executequery(query); results.add(result); } return results; }
Comments
Post a Comment