jeudi 19 avril 2018

Best way to avoid complicated if else branching - Java

I have rest API which uses several parameters ( as requestparams) to search entity. There could be multiple variations of this search. Following methods get calls at the end for searching entity with given parameters.

public List<Person> searchPerson(final String name, 
           final String city, final String state, final String code) {
    if( name != null && city != null && state != null && code != null ){
        //Search person in database with above all parameters
        //personRepositoy is spring data repository. 
        personRepositoy.findByNameAndCityAndStateAndCode(name, city, state, code);
    } else if( city != null && state != null && code != null){
        personRepositoy.findByCityAndStateAndCode(name, city, state, code)
    }
}

Is there a way I can avoid complicated ( error prone , not so easy to refactor) branching here ? May be using Collections or functional programming concept ? I really not comfortable writing this kind of branching code ( since these are hard to maintain)

Aucun commentaire:

Enregistrer un commentaire