Delegate vs Callback in Java

23,350

Solution 1

This is a callback. According to Wikipedia:

In computer programming, a callback is a reference to a piece of executable code that is passed as an argument to other code.

So let's look at the executable code:

public void getHelp(HelpCallback callback){
    //do something
    callback.call(OK);
}

Here, the callback argument is a reference to an object of type HelpCallback. Since that reference is passed in as an argument, it is a callback.

An example of delegation

Delegation is done internally by the object - independent of how the method is invoked. If, for example, the callback variable wasn't an argument, but rather an instance variable:

class MyDriver {

    public static void main(String[] argv){
        // definition of HelpStrategy omitted for brevity
        MyObject myObj = new MyObject(new HelpStrategy() {
            @Override
            public void getHelp() {
                System.out.println("Getting help!");
            }
        });
        myObj.getHelp();
    }

}

class MyObject {
    private final HelpStrategy helpStrategy;

    public MyObject(HelpStrategy helpStrategy) {
        this.helpStrategy = helpStrategy;
    }

    public void getHelp(){
        helpStrategy.getHelp();
    }
}

... then it would be delegation.

Here, MyObject uses the strategy pattern. There are two things to note:

  1. The invocation of getHelp() doesn't involve passing a reference to executable code. i.e. this is not a callback.
  2. The fact that MyObject.getHelp() invokes helpStrategy.getHelp() is not evident from the public interface of the MyObject object or from the getHelp() invocation. This kind of information hiding is somewhat characteristic of delegation.

Also of note is the lack of a // do something section in the getHelp() method. When using a callback, the callback does not do anything relevant to the object's behavior: it just notifies the caller in some way, which is why a // do something section was necessary. However, when using delegation the actual behavior of the method depends on the delegate - so really we could end up needing both since they serve distinct purposes:

    public void getHelp(HelpCallback callback){
        helpStrategy.getHelp(); // perform logic / behavior; "do something" as some might say
        if(callback != null) {
            callback.call(); // invoke the callback, to notify the caller of something
        }
    }

Solution 2

I'd argue that "callback" is a name for a generic pattern where you provide the module you're calling with a a way for said module to call your code. A C# delegate, or an ObjC delegate object, (these two being entirely different beasts) or a Java class-implementing-the-callback-interface are different, platform-specific ways of implementing the callback pattern. (They can also themselves be considered patterns.) Other languages have more or less subtly different ways of doing so.

The above concept of "delegate" is also similar to the Strategy pattern, where the delegate can be thought of as one. Similarly, a Visitor is also a type of callback. (A visitor is also a strategy for processing each visited item.)

All this is using definitions that are intuitive to me, and might not be to anyone else, because neither "callback" or "delegate" are formal terms and it makes little sense to discuss them without referring to a previous definition thereof that's valid in your context. Consequently it makes little sense to ask what the definition is since, to the best of my knowledge, there isn't an authoritative one. To wit, the fact that other answers to this question are likely to say something entirely different.

My recommendation would be to focus on the merits of your design – whether it achieves what you need, doesn't introduce tight coupling, etc. – rather than on minutiae of semantics. When two design patterns appear similar, they probably can be used to achieve similar goals equally well.

Solution 3

What you want to achieve is bidirectional communication between the original caller and a service while avoiding the service to depend on the client. The pattern you use for that goal often depends on the restrictions of your language. You use function pointers, closures or, if you have none of these, callback objects (which might also be seen as closures).

And then there are often lots of different names for the same or a very similar pattern.

Share:
23,350

Related videos on Youtube

pvllnspk
Author by

pvllnspk

Android developer, iOS enthusiast.

Updated on January 05, 2020

Comments

  • pvllnspk
    pvllnspk over 4 years

    I have some misunderstanding about terms of delegates and callbacks in Java.

    class MyDriver {
    
        public static void main(String[] argv){
            MyObject myObj = new MyObject();
            // definition of HelpCallback omitted for brevity
            myObj.getHelp(new HelpCallback () {
                @Override
                public void call(int result) {
                    System.out.println("Help Callback: "+result);
                }
            });
        }
    }
    
    class MyObject {
    
        public void getHelp(HelpCallback callback){
            //do something
            callback.call(OK);
        }
    }
    

    Is it callback or delegate (Are delegates and callbacks the same or similar?)?

    How to implement then another one?

    • Montre
      Montre over 11 years
      Based on which definition of "delegate" and "callback"? Delegate means a bunch of things based on context, for instance the Objective-C and C# meanings are significantly different.
    • pvllnspk
      pvllnspk over 11 years
    • pvllnspk
      pvllnspk over 11 years
      I am interested only contexts of Java and Objective C(I want to know how to implement it in pure Java).
    • Montre
      Montre over 11 years
      The accepted answer in that one talks about C# which is obviously not your case. Also, you can't just say "for example". My point is there isn't really a hard and fast distinction between design patterns even if you're being really, really pedantic.
    • pvllnspk
      pvllnspk over 11 years
      I am little confused, because starting learning Objective C I faced with delegates that seems very similar to java callbacks -> so I want to feel difference between them.
    • pvllnspk
      pvllnspk over 11 years
      found an interesting topic: stackoverflow.com/questions/1015608/…