Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to design a method for search?

I am designing a decorator class which wraps a news search engine, so we can ship this class with a library to be used by other teams.

The exposed interface of this class is a Java-styled one, it takes a lot of parameters, then this decorator assembles these parameters as a search text to the search engine.

My method is something like the following:

public List<News> search(List<String> keywords, List<String> categories, List<String> authors, List<Location> locactions, List<LocalDate> dates, List<SortRule> sortRules, int offset, int limit);

Yes, I know... This method looks ridiculously long, very error-probe and hard to use for the clients.

So, how can I design a better API for such a search functionality?

like image 488
Fred Pym Avatar asked Apr 22 '16 04:04

Fred Pym


2 Answers

You can try writing a wrapper class for applying the rule filters and then take the new object of this class in your current class. This way it would be much simple and cleaner.

For Example,

RuleFilters r = new RuleFilters();
r.addFilters(Type.Keywords, keywords);
r.addFilters(Type.Categories, categories);
r.addFilters(Type.Authors, authors);

Here Type is an enum which holds the details of the different rule filters like {Categories, Authors, Keywords} etc.

Finally in your Main Class:

public List<News> search(RuleFilters r) {
    /* Do Something with the rule filters */ 
};

Interface:

List<News> search(RuleFilters r);

Note: public keyword is not necessary in interfaces.

like image 166
user2004685 Avatar answered Sep 20 '22 00:09

user2004685


As noted in Effective Java,You may consider using Builder Pattern. And that would be neat solution.

SearchParam search = new SearchParam.Builder(keywords).
  categories(categories).authors(authors).location(loc1,loc2).build();
like image 23
Chirag Avatar answered Sep 18 '22 00:09

Chirag