Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor method reference to support parameter(s)

I want to generify method reference to trigger methods per type,

I save Map of Function Interfaces by key, the functions will call services method, but I have an issue that I can't define paramater using method reference, e.g.:

 private Map<Type, Function<User, Boolean>> functionInterfaces = new HashMap<>();
 {
    functionInterfaces.put(Type.MY_TYPE1, MyService::myTypeMethod1);
    functionInterfaces.put(Type.MY_TYPE2, MyService::myTypeMethod2);
    functionInterfaces.put(Type.MY_TYPE3, MyService::myTypeMethod3);
 }

Currently I need to create method per type

private boolean myTypeMethod1(Parameters parameters) {
    return myGenericTypeMethod(parameters, Type.MY_TYPE1);
}
private boolean myTypeMethod2(Parameters parameters) {
    return myGenericTypeMethod(parameters, Type.MY_TYPE2);
}

I call function using apply:

if (map.containsKey(key)) {
    map.get(key).apply(new Parameters.Builder().build());
}

Can I refactor code to use single method?

like image 790
user7294900 Avatar asked Sep 14 '25 00:09

user7294900


1 Answers

The problem with this

functionInterfaces.put(Type.MY_TYPE1, MyService::myTypeMethod1);

is that MyService::myTypeMethod1 is an instance method. It must take a MyService, because that is the instance to be acted upon. You are trying assign it to Function<User, Boolean>, but where is the instance in this case?

I don't know whether it makes sense to because we don't have much context, but changing the declaration to

Map<Type, BiFunction<MyService, Parameters, Boolean>> functionInterfaces = ...

would at least solve the compiler's problem.

In this case, it acts upon MyService, takes a Parameter and returns a Boolean.


Alternatively - and, again, we have limited context - making the MyService methods static would be sufficient, but you can only do that if they don't require any state.

like image 171
Michael Avatar answered Sep 15 '25 15:09

Michael