First Responder: A Dynamic Heaven
I grew up with programming languages like Pascal, C, C++ and later Java. All of these languages have a rather static type system. The compiler of these languages can do a lot of good things. It checks for example if you try to use functions that are not valid in a particular context.
These kind of static programming is good for a number of cases and perhaps it’s the best environment for many mission critical systems. At least every bug that is being found by the compiler must not be found by QA.
But this life belt comes at a cost.
Any kind of framework or library needs to be flexible and reusable as much as possible/necessary. Static typing and maximal flexibility often do not match very well. A number of design patterns show up in static typed languages more often than in dynamic typed languages. Dynamic languages already provide enough flexibility out of the box.
When you have done a lot of programming in static typed languages it is easy to miss the goodies of dynamic languages.
Cocoa provides a mechanism called First Responder. I have read about it in my early Cocoa days but soon have lost the knowledge about it in my static typed brain.
The First Responder is a mechanism with which you can bind an user interface element to a method of an unknown object. Pretty dynamic. During runtime the First Responder is represented by different objects dependent on the state of the UI (focus element, open windows, …). Whenever the First Repsonder changes the Cocoa framework checks if the object responds to the bound action. If it does the user may use the interface element and trigger the action.
With this simple mechanism you can define menu items that will be enabled for certain windows (First Reponders) only. The whole mechanism is enhanced by a variant of the Chain of Responsibility pattern to make this thing a killer feature.
Doing something similar with Java will be - well - difficult.
Some time ago I stumbled over some piece of code from Rentzsch in order to have support for the Delete key in table views when using bindings. I wanted to bring up some kind of confirmation dialog before doing a delete. But I also wanted to keep the code as reusable as possible. The code for the confirmation should be in my controllers. Thanks to First Responder it is as easy as the following
if ([self sendAction:@selector(willRemoveSelectionFromTableView:) to:nil] == NO) {
[[valueBindingDict objectForKey:@"NSObservedObject"] remove:self];
}
The sendAction to nil triggers a first responder search for an object that responds to willRemoveSelectionsFromTableView. With this I can implement any specific things in my controllers while still having a reusable core logic.
That’s a solution I’m pretty happy with. I’m in dynamic heaven…
March 22nd, 2007 at 11:00 pm
To be precise, the mechanism is called the “responder chain”.
-jcr