1
public class A {
  public void search(boolean[] searchList) {
    // searchList array is used to identify what options to search for in a 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 a query to search for all Ls
    if(searchM == true) // write a query to search for all Ms
    ...........
}

Is there a way I can simplify this code ?

@All : Sorry for posting a wrong question before. I was confused!

Thanks, Sony

2
  • using booleans allows them all to be true. You need to look at how these booleans are set and set a single field instead, then you can use a switch. Commented Feb 18, 2011 at 15:45
  • What sets the boolean values in your real application? Commented Feb 18, 2011 at 15:45

5 Answers 5

5

I am a big fan of enums:

public class A {
  enum SearchType {
   L, M, A, K;
 }
  public void search(SearchType type) {

    switch (type) {
     case L: 
          System.out.println("Searching for L");
          break;
     case M:
          System.out.println("Searching for M");
          break;
     case A: 
          System.out.println("Searching for A");
          break;
     case K:
          System.out.println("Searching for K");
          break;
     default:
          System.out.println("what to do here?");
          // throw exception?
}

note also: your scenario allowed more than one search boolean to be true at a time, I assumed that was not your goal, but if it is we can tweak this a bit.

Sign up to request clarification or add additional context in comments.

8 Comments

@Nathan beaten by an Enum! I do need to learn this concept, cleaner than static int's
If you can do this you could do System.out.println("Searching for "+type); instead of a switch ;)
@Blundell yes, If I could change on thing about java it would be to push enums back to the beginning of the language, many libraries could just suck less with type safety.
I would personally love to see Enumeration disapper in favor of Iteratable. One step that in the right direction (that keeps faltering) is project Jigsaw. Whether OSGi beats it out or not, if we modularized Java, then we could talk about requiring X version of the JVM library. One would hope that you could then pick the version that didn't have X. (or merged the swing / awt stuff into one heirarchy).
@Edwin: enum != Enumeration.
|
2

You should convert your state into an enum. For example your search booleans seem to be exclusive so i would do something like this:

enum SearchOption {
  searchA, searchK, searchL, searchM
}

// then you can do 

SearchOption searchOption = searchA;

switch (searchOption) {
  case searchA: 
    System.out.println("I am searching for A");
    break;
  case searchK: 
    System.out.println("I am searching for K");
    break;
  case searchL: 
    System.out.println("I am searching for L");
    break;
  case searchM: 
    System.out.println("I am searching for M");
    break;    
}

If your states aren't exclusive you should try build to build a super set of exclusive states initially.

4 Comments

Toader, you type rather quickly. I'll delete my nearly identical posting.
@Edwin :)) Sorry about that :). I did trained myself to touch type at some point :).
not a problem at all. I could do 65 wpm in better days. Still have nightmares where I'm infront of a Selectric hearing "b" "b" "b" space!
@Edwin :)) yep .. true that :(.
2

Why don't employ OOP? Like:

public interface Seeker {
   void seek();
}
public class LSeeker implements Seeker {
   void seek() { System.out.println("Will search for L"); }
}
// ... More implementations of Seeker
public class SeekDriver {
   void seek(Seeker seeker) { seeker.seek(); }
}

3 Comments

How does that address the question? The program would still need to select at some point which Seeker to instantiate.
@Dave Costa: Yep, low-level factory will use 'switch' or 'if' to create implementation. However, it seems OP codes' concerned not with creation of objects, but with some kind of algorithm. OOP suits better here.
It doesn't answer the question, but it solves the problem. Sometimes people just want an answer to their question, but sometimes they benefit more greatly by being directed to a better solution.
1
public class A {

    public enum SearchOption {
        SEARCH_L,
        SEARCH_M,
        SEARCH_A,
        SEARCH_K;
    }
    /**
     * Make them pass in an enum for your search.
     * Pros: type safe, can only use the selections you give
     * Cons: must add to the enum to add new types
     * @param option
     */
    public void enumSearch(SearchOption option) {

        switch(option) {
        case SEARCH_A:
            System.out.println("I am searching for A");
            break;
        case SEARCH_K:
            System.out.println("I am searching for K");
            break;
        case SEARCH_L:
            System.out.println("I am searching for L");
            break;
        case SEARCH_M:
            System.out.println("I am searching for M");
            break;
        }
    }

    /**
     * Use a primitive for your input
     * Pros: Gives you more options without updating the enum
     * Cons: Users could enter input you don't really want them to use
     * @param option
     */
    public void charSearch(char option) {
        switch(option) {
        case 'a':
        case 'A':
            System.out.println("I am searching for A");
            break;
        case 'k':
        case 'K':
            System.out.println("I am searching for K");
            break;
        case 'l':
        case 'L':
            System.out.println("I am searching for L");
            break;
        case 'm':
        case 'M':
            System.out.println("I am searching for M");
            break;
        }
    }

    /**
     * Use a primitive and don't even actually check it! Just run with it!
     * @param option
     */
    public void uncheckedSearch(char option) {
        System.out.println("I am searching for " + option);
    }
}

As per your comment, here's my updated example of that method - make sure the comment at the top is updated!

/**
 * Perform the search based on the options provided
 * The list should be in the order of L, M, A, K
 * @note update this comment as more search options are added
 * @param searchList the list of flags indicating what to search for
 */
public void search(boolean[] searchList) {

    // as per docs, [0] denotes an L search:
    if(searchList[0]) 
        // write a query to search for all Ls

    // as per docs, [1] denotes an M search:
    if(searchList[1]) 
        // write a query to search for all Ms

    // as per docs, [2] denotes an A search:
    if(searchList[2]) 
        // write a query to search for all As

    // as per docs, [3] denotes a K search:
    if(searchList[3]) 
        // write a query to search for all Ks
}

Latest idea:

// Use the SearchOption enum from 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;

}

5 Comments

Hi! Sorry for the trouble but I was confused with my goal. I edited my question. Could you please look into it ? Thanks !!!!
I tried this code earlier but I was wondering if there is a way to use switch. If this is the simplest approach, I would go ahead with this..Thanks Again!!
Well, if you want to be able to search both K and L, then no there isn't a way other than this. If you know you only want one search at a time, then adapting my answers above are the better approach.
Yes, I should be able to search for both K and L. Thanks again !
@sony I edited in the new idea. Obviously you need to opulate searches with your queries ahead of time.
0

Like this: ?

public class A {
  public void search() {

    private static final int SEARCH_L = -1;
    private static final int SEARCH_M = 0;
    private static final int SEARCH_A = 1;
    private static final int SEARCH_K = 2;

int status;

switch(status){
 case SEARCH_L:
    System.out.println("I am searching for L");
  break;
 case SEARCH_M:
    System.out.println("I am searching for M");
  break;
 // Etc

 default:
    // Log error didn't hit a known status
   break;
}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.