Search code examples
javafunctionjava-8dispatch

Convert multiple if statements to dispatch functions


I am struggling to find a way to dispatch this to functions in java8

    Person p = registry.getPerson();

    if (field == Field.LASTNAME) {
        p.setLastName(str);
    }
    if (field == Field.FIRSTNAME) {
        p.setFirstName(str);
    }
    if (field == Field.MIDDLENAME) {
        p.setMiddleName(str);
    }

My idea is to use some kind of function dispatch table to replace the if statements in the case of more cases:

Map<Integer, Function> map = new HashMap<Integer, Function>  
static {
    map.put(1, new Function<String, String>() {
        @Override
        public Object apply(String str) {
            person.setLastName(str);
            return str;
        }
    }
}

But the code cannot compile, because i need to pass the person object some place. Anyone knows a pattern for this?


Solution

  • Instead of storing Function<String,String>, you can store BiFunction<Person,String,String> and pass the Person instance in as a parameter.

    Map<Integer, BiFunction<Person,String,String>> map = 
            new HashMap<Integer, BiFunction<Person,String,String>>();  
    static {
        map.put(1, (person, str)->person.setLastName(str));
    
    }
    

    In the interest of simplicity, you could also just store a List of the functions, if you're just going to index them by an integer, it's faster for random access and makes for less complicated generic code:

    List<BiFunction<Person,String,String>> list = new ArrayList<BiFunction<Person,String,String>>();  
    static {
        list.add((person, str)->person.setLastName(str));
    }