Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent of Cocoa delegates / Objective-C informal protocols?

What is the Java equivalent of Cocoa delegates?

(I understand that I can have an interface passed to a class, and have that class call the appropriate methods, but I'm wondering if there is any other way to achieve something closer to Cocoa/Objective-C's informal protocols)

like image 834
Debajit Avatar asked Jul 30 '09 23:07

Debajit


1 Answers

The short answer is there's nothing in Java as close as you'd like, but there are alternatives. The delegate pattern isn't hard to implement, it's just not quite as convenient as doing it with Objective-C.

The reason "informal protocols" work in Objective-C is because the language supports categories, which allow you to add methods to existing classes without subclassing them, or even having access to the source code. Thus, most informal protocols are a category on NSObject. This is clearly impossible in Java.

Objective-C 2.0 opts for @optional protocol methods, which is a much cleaner abstraction and preferred for new code, but even further from having an equivalent in Java.

Honestly, the most flexible approach is to define a delegate protocol, then have classes implement all the methods. (With modern IDEs like Eclipse, this is trivial.) Many Java interfaces have an accompanying adapter class, and this is a common approach for not requiring the user to implement a lot of empty methods, but it restricts inheritance, which makes code design inflexible. (Josh Bloch addresses this in his book "Effective Java".) My suggestion would be to only provide an interface first, then add an adapter if it's truly necessary.

Whatever you do, avoid throwing an UnsupportedOperationException for "unimplemented" methods. This forces the delegating class to handle exceptions for methods that should be optional. The correct approach is to implement a method that does nothing, returns a default value, etc. These values should be well documented for methods that don't have a void return type.

like image 76
Quinn Taylor Avatar answered Oct 23 '22 04:10

Quinn Taylor