Back from a week of studying Cocoa
As a wise man (Brent Simmons of NetNewsWire fame) once said in a blog post explaining MySQL to Frontier users: "Old programmer’s philosophy: if you work primarily (or exclusively) in one environment, it’s a good idea to learn about others. It stretches your mind, helps you think more widely and imaginatively about how to solve problem".
For the past week, I've been studying Cocoa and Objective-C by reading Cocoa Programming for Mac OS X (Second Edition), by Aaron Hillegass, which came recommended and is definitely the best book I've seen about Cocoa programming. The author always brings a smile to my face, not just from his clear and warm writing style, but also the fact that he wears this huge cowboy hat all the time. It's been quite interesting and exciting and its definitely been a mind-stretching experience. There's a lot in Objective-C that Java could learn from, plus things in Cocoa for other desktop frameworks. (And vice-versa, of course.)
Here's one example: in Objective-C, you don't have an actionListener type framework, with actionListeners that either do work or delegate to other classes. Instead, you've got actions and targets, where if you press a button, you can tell another class to directly do something, instead of going though an actionListener.
For example: if you had a button that generated a random number, in Java/Swing, you'd have something like:
myJButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent anEvent ) {
randomNumberGenerator.generate();
}
} );
In SWT, you use selectionListeners. The code would look like:
myButton.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent anEvent ) {
randomNumberGenerator.generate();
}
} );
In Objective-C/Cocoa, you'd visually wire a button in a program called Interface Builder to an instance of RandomNumberGenerator, by control-dragging from the button to the instance (called a target from the button's point of view). Then you'd pick a method to call (which is called an action). The end result is less code to maintain (actually zero lines of code vs 5 lines of code each for Swing and SWT) and a more direct mapping of the programmer's intent: in this case, to generate a random number when the button is pushed.