I am currently implementing a Rest API for search query. The method takes multiple filter parameters, such as keyword, name, title, description, date, etc. In order to stay DRY and avoid repeated if else clause, I am looking for the best practices way to retrieve the resource from database. Lets say the database exposes two methods, findByUsername(...) and findByDescription(), and we want to expose them through a restful web interface. A naive implementation will be using if and else clause similar to below.
@GET
@Path("users")
public User getUsers(@QueryParam("username") String username,
@QueryParam("description") String description) {
User user = null;
if (username != null) {
// execute findByUsername method to the database
user = findByUsername(username);
} else if (description != null) {
// execute findByDescription method to the database
user = findByDescription(description);
}
return user;
}
The question is how to improve the code above in order to avoid redundant if else (checking) clause and keep staying DRY? I am implementing the web services using Jersey JaxRS 2.0