mercredi 13 juin 2018

Optimizing multiple if-else condition in Java

I have a REST API which will provide search results based on specific search criteria. User can search using Department Id, User Id and Joined Date. So here, user can search in 7 different combinations.

  1. Search only with Dept Id
  2. Search only with User Id
  3. Search only with Joined Date
  4. Search with Dept Id & User Id
  5. Search with User Id & Joined Date
  6. Search with Dept Id & Joined Date
  7. Search will all 3 criteria (Dept Id, User Id & Joined Date)

According to our application's current design, For each criteria I would have to call different services in different order for information.

For instance : We have an existing User service which has user details, a Department service which has details. So if user searches only for User ID, I would directly go to UserService. If user searches with Dept ID & User I would first have to query Dept service and then the User service.

My current code is:

if(Util.hasOnlyUserId(searchCriteria)) {
        searchResponse = searchWithUserId(searchRequest);
    } else if(Util.hasOnlyJoinedDate(searchCriteria)) {
        searchResponse = searchWithDate(searchRequest);
    } else if (Util.hasOnlyDeptID(searchCriteria)) {
        searchResponse = searchWithDeptId(searchRequest);
    } else if (Util.hasUserIdAndDeptId(searchCriteria)) {
        searchResponse = searchWithUserIdAndDeptId(searchRequest);
    } else if (Util.hasUserIdAndDate(searchCriteria)){
        searchResponse = searchWithUserIdAndDate(searchRequest);
    } else if (Util.hasDeptIdAndDate(searchCriteria)) {
        searchResponse = searchWithDeptIdAndDate(searchRequest);
    } else if (Util.hasAllCriteria(searchCriteria)) {
        searchResponse = searchWithAllCriteria(searchRequest);
    }

Here, searchCriteria is my request object (POJO) which has these search elements as private members.

I have been trying to optimize this multiple if-else condition in other words, avoid having this multiple condition. I tried to separate each of them and put them into different methods. But this just isn't satisfying me and it seems like it is in an un-optimizable state.

Any ideas on how I can go about doing this would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire