user1659473
user1659473

Reputation: 21

Code solution to avoid if else conditions

I am wondering if anyone can suggest me a design pattern or best way to code the below problem.

1) I have an array list of books like the below

list.add(new Book(title, author);
list.add(new Book(title1, author1);

and so on....

2) And now I would like to find all the books from the list by author

findByAuthor(String author) {
  for(Book book : list){
    if(book.getAuthor().equals(author)){
      return book;
    }
  }
}

Like wise I have another method called findByTitle(). But, it would be same code except book.getAuthor() will have to be book.getTitle(). Everything will be same.

3) Now i can write a method which is generic to both methods like below;

findByBookProperty (String type, String propertyValue){
  for(Book book : list)
    if(type.equals("author") && book.getTitle().equals(propertyValue)){
      return book;
    } //another else if for author
    //another else for another property
    // if else repeats for all the required finder types...
  }
}

4) The problem i have here is; 1. I dont want to use the nasty if/else condition for the finder types. 2. I want to know if there is any design pattern or better way to handle this if else or swich method.

Important note: I get the author name as a request parameter value in my spring controller method.

I appreciate your thoughts.

Upvotes: 1

Views: 146

Answers (1)

Isaac
Isaac

Reputation: 16736

Use Commons-Collections' Predicates framework:

1) Construct a Predicate instance for each type of test.

2) Use CollectionUtils.select(), passing in the predicate you'd like to use for evaluating objects.

Another alternative is to use Commons-Collections' Transformation framework:

1) Write a Transformer for each type of property you'd like extracted/compared against.

2) Write a generic loop, accepting a Transformer instance as a parameter.

Upvotes: 3

Related Questions