Saturday, October 13, 2012

Understanding Callbacks with Java - Inversion of control

Callback Pattern in Java Environment


Hi there! today i wanna share something with you, that it is very common and widely used in javascript for example. I'm speaking of callbacks. Do you know how and when this "pattern" is used? Do you really understand it in a java context (environment)? Well i was asking me also some of those questions and that's the reason i started to learn more about it. The ideia behind it is the inversion of control (abbreviated IoC). This paradigma describes the way frameworks work. It is also known as the "Hollywood principle - Don't call me, we will call you"

Simplified Callback pattern in Java just to understand it. Concrete example follows bellow.




interface CallBack {
    void methodToCallBack();
}

class CallBackImpl implements CallBack {
    public void methodToCallBack() {
        System.out.println("I've been called back");
    }
}

class Caller {

    public void register(CallBack callback) {
        callback.methodToCallBack();
    }

    public static void main(String[] args) {
        Caller caller = new Caller();
        CallBack callBack = new CallBackImpl();
        caller.register(callBack);
    }
} 

Ok you may be asking you, when this usefull or may be asking you what's the difference between calling directly callback.methodToCallBack() right?

ANSWER: well, this example just shows to you how to construct such a callBack function when working in a java environment. Certainlly it doesn't make it any sense to use it that way. Let's get a little deeper into a concrete useful example now.

The idea behind it is the "INVERSION OF CONTROL". Let's take a timer as a realistic example. Let's supose that you know, that a specific timer supports callback functions every hour. Exactly it means, that every hour, the timer will call your registed call method function.

Conctrete Example:

Let's say we wanna update the time of a website every hour. Here is the UML of the following example:


Callback Interface

Let's define first the callback interface:


import java.util.ArrayList;
import java.util.List;

// For example: Let's assume that this interface is offered from your OS to be implemented
interface TimeUpdaterCallBack {
    void updateTime(long time);
}

// this is your implementation.
// for example: You want to update your website time every hour
class WebSiteTimeUpdaterCallBack implements TimeUpdaterCallBack {

    @Override
    public void updateTime(long time) {
        // print the updated time anywhere in your website's example
        System.out.println(time);
    }
}

The SystemTimer that supports Callback functions in our example:



// This is the SystemTimer implemented by your Operating System (OS)
// You don't know how this timer was implemented. This example just
// show to you how it could looks like. How you could implement a
// callback by yourself if you want to.
class SystemTimer {

    List<TimeUpdaterCallBack> callbacks = new ArrayList<TimeUpdaterCallBack>();

    public void registerCallBackForUpdatesEveryHour(TimeUpdaterCallBack timerCallBack) {
        callbacks.add(timerCallBack);
    }

    // ... This SystemTimer may have more logic here we don't know ...

    // At some point of the implementaion of this SystemTimer (you don't know)
    // this method will be called and every registered timerCallBack
    // will be called. Every registered timerCallBack may have a totally
    // different implementation of the method updateTime() and my be
    // used in different ways by different clients.
    public void oneHourHasBeenExprired() {

        for (TimeUpdaterCallBack timerCallBack : callbacks) {
            timerCallBack.updateTime(System.currentTimeMillis());
        }
    }
}

And finally our WebSiteTimeUpdater which is our client in this fictive and simple example:



// This is our client. It will be used in our WebSite example. It shall update
// the website's time every hour.
class WebSiteTimeUpdater {

    public static void main(String[] args) {
        SystemTimer SystemTimer = new SystemTimer();
        TimeUpdaterCallBack webSiteCallBackUpdater = new WebSiteTimeUpdaterCallBack();
        SystemTimer.registerCallBackForUpdatesEveryHour(webSiteCallBackUpdater);
    }
}

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO 😱👇

Be sure to read, it will change your life!
Show your work by Austin Kleon: https://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practices: https://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO 😱👆