DEV Community

Partha Sutradhar
Partha Sutradhar

Posted on

Design Callback Pattern in Java for WorkerContext

Introduction

Callbacks are a prominent programming paradigm in Java that is used for asynchronous and event-driven programming. Callbacks were traditionally created and used by establishing interfaces and putting them into anonymous inner classes, which could result in verbose and crowded code. But lambda expressions, which offer a more concise and expressive method of working with callbacks, were introduced in Java 8.

We'll look at a real-world example in this blog article to see how lambda expressions can make using callbacks in Java easier. We will compare the lambda approach with the old method using a WorkerContext class that uses callbacks to accomplish some work.

Design Callback Pattern

Let's begin by discussing the traditional approach to callbacks pattern in Java.

interface Callback {
    void call(int data);
}

class WorkerContext {
    private Callback callback;

    public WorkerContext() {}

    public WorkerContext(Callback callback) {
        this.callback = callback;
    }

    public void startWork(int min, int max) {
        if (callback != null) {
            callback.call(ThreadLocalRandom.current().nextInt(min, max + 1));
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The conventional way involves defining a Callback interface with a single call method, utilising an anonymous inner class to generate an instance of the interface, and passing it to the WorkerContext.

Traditional Way

class Solution {
    public static void main(String[] args) {
        Callback callback = new Callback() {
            @Override
            public void call(int data) {
                System.out.println("Random : " + data);
            }
        };
        WorkerContext workerContext1 = new WorkerContext(callback);
        workerContext1.startWork(0, 100);
    }
}
Enter fullscreen mode Exit fullscreen mode

Lambda Way

Now, let's explore how lambda expressions can simplify the callback process.

class Solution {
    public static void main(String[] args) {
        WorkerContext workerContext2 = new WorkerContext((count) -> System.out.println("Random : " + count));
        workerContext2.startWork(0, 100);
    }
}
Enter fullscreen mode Exit fullscreen mode

When constructing the WorkerContext instance via the lambda method, we explicitly describe the callback at that point. As a result, anonymous inner classes and a separate interface specification are not required.

Conclusion

Using functional programming concepts in your Java applications is made possible by adopting the lambda approach, which also increases code readability and maintainability.

Top comments (0)