26 August 2011

Implemet callbacks using callback interfaces

SA,

While I am fasting now (there are about 2 hours left for the breakfast), I'd like to talk about some very important usage of interfaces...

I am here by interfaces mean the types that contains only function prototypes.
The interfaces found in many programming language like Java, C# and others.

I'll not talk about any particular programming language here, although, the code samples will be pseudocode.

Suppose We want to build some Generic function that draw a button on the screen and execute it:
1.
2.
3.
4.
5.
6.
7.
void drawButton(Panel container, String buttonName)
{
    Button b = new Button();
    b.setName(buttonName);
    container.add(b);

}
Now we need to add the functionality to the button, but remember this is a generic module, so the functionality will be provided by the module user.

We can modify our code to appear like:
1.
2.
3.
4.
5.
6.
7.
8.
void drawButton(Panel container, String buttonName, int (*onClick) (Button b))
{
    Button b = new Button();
    b.setName(buttonName);
    container.add(b);
    (*onClick) (b);
    
}

Now, the use can send a pointer to a function that will execute the action when the button is clicked.

The solution above can work for language that support function pointers such as C, C++ (Javascript also support passing functions as parameters, and FP langs too)

But what is the language doesn't support function pointers such as Java..

In this case, Interfaces are used and it called then, Callback interfaces...

Let's rewrite our sample:
1.
2.
3.
4.
5.
6.
7.
8.
Button drawButton(Panel container, String buttonName, Clickable clickable)
{
    Button b = new Button();
    b.setName(buttonName);
    container.add(b);
    clickable.onClick(b);
    return b;
}
And here's the code Clickable interface:
1.
2.
3.
4.
5.
public interface Clickable
{
     public void onClick(Button b);
}

So The user to call the above function, it should provide an implementation for the Clickable interface and its onClick function.

Example calling the function:

1.
2.
3.
4.
5.
6.
7.
8.
9.
drawButton(containerPanel, "Go To HomePage", new Clickable()
{
    public void onClick(Button b)
    {
        // do the button action here.
    }
} );

No comments: