Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Functional Programming - Passing function along with its argument

I have a question on Java 8 Functional Programming. I am trying to achieve something using functional programming, and need some guidance on how to do it.

My requirement is to wrap every method execution inside timer function which times the method execution. Here's the example of timer function and 2 functions I need to time.

timerMethod(String timerName, Function func){
  timer.start(timerName)
  func.apply()
  timer.stop()
}

functionA(String arg1, String arg2)

functionB(int arg1, intArg2, String ...arg3)

I am trying to pass functionA & functionB to timerMethod, but functionA & functionB expects different number & type of arguments for execution.

Any ideas how can I achieve it.

Thanks !!

like image 395
user2751441 Avatar asked Aug 15 '26 14:08

user2751441


1 Answers

you should separate it into two things by Separation of Concerns to make your code easy to use and maintaining. one is timing, another is invoking, for example:

//                                       v--- invoking occurs in request-time
R1 result1 = timerMethod("functionA", () -> functionA("foo", "bar"));
R2 result2 = timerMethod("functionB", () -> functionB(1, 2, "foo", "bar"));


// the timerMethod only calculate the timing-cost
<T> T timerMethod(String timerName, Supplier<T> func) {
    timer.start(timerName);
    try {
        return func.get();
    } finally {
        timer.stop();
    }
}

IF you want to return a functional interface rather than the result of that method, you can done it as below:

Supplier<R1> timingFunctionA =timerMethod("A", ()-> functionA("foo", "bar"));
Supplier<R2> timingFunctionB =timerMethod("B", ()-> functionB(1, 2, "foo", "bar"));


<T> Supplier<T> timerMethod(String timerName, Supplier<T> func) {
    //      v--- calculate the timing-cost when the wrapper function is invoked
    return () -> {
        timer.start(timerName);
        try {
            return func.get();
        } finally {
            timer.stop();
        }
    };
}

Notes

IF the return type of all of your functions is void, you can replacing Supplier with Runnable and then make the timerMethod's return type to void & remove return keyword from timerMethod.

IF some of your functions will be throws a checked exception, you can replacing Supplier with Callable & invoke Callable#call instead.

like image 199
holi-java Avatar answered Aug 20 '26 05:08

holi-java



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!