You could use the Runnable
functional interface.
Its function descriptor is () -> void
.
It suits perfectly for your need as the mapping operation returns no result and you don't need to specify any parameter as input of the function either.
Indeed here : myObject.putA(a)
, you don't want to pass the a
parameter to the function.
You want rather pass the whole expression myObject.putA(a)
as a lambda body :
() -> myObject.putA(a);
You could so write this mapElement()
method :
public static void mapElement(Runnable mapProcessor) {
// Retry logic
try {
mapProcessor.run();
} catch (Exception e) {
// exception handling
}
}
Note that to catch any Java exception (both checked and runtime), you have to catch RuntimeException
rather than Exception
.
And you can use mapElement()
in this way :
MyObject myObject = new MyObject();
...
mapElement(() -> myObject.putA(a));
mapElement(() -> myObject.putB(b));
mapElement(() -> myObject.putC(c));
Runnable
may not convey the expected meaning as it was primarily
designed for thread execution.
If it makes sense you also may introduce your own functional interface.
With this way, you may also declare any specific checked exception in the function if it appears relevant.
Which is not possible with Runnable
.
For example :
@FunctionalInterface
public interface MapProcessor{
void map() throws MappingException;
}
You could so use it in this way :
public static void mapElement(MapProcessor mapProcessor) {
// Retry logic
try {
mapProcessor.map();
}
catch (MappingException e) {
// Mapping exception handling
}
catch (Exception e) { // or RuntimeException if more relevant
// other exception handling
}
}