views:

283

answers:

2

Why does cocoa use delegates rather than inheritance?

+5  A: 

In general creating a subclass can be a time consuming process, requiring a lot of groundwork, and overriding various template methods.

Meanwhile, using a delegate allows you to create a simple object that answers a few specific question or reacts in various ways.

Now when you combine this with the dynamism that you can achieve by swapping out delegates on the fly it can create a very flexible robust system that promotes more code reuse.

There is some general discussions regarding these things here and here. You can also find some older SO questions here and here.

Bryan McLemore
How does a template take less effort to create than a subclass? On the other hand, the ability to swap out on the fly could be useful in some circumstances, but I don't see why it is necessary for Cocoa.
Casebash
I'm not even so much sure that it's less work, but fewer levels of inheritence leads to a generally simpler design. Simplicity is a Good Thing (tm).
Bryan McLemore
As to Necessity. Nothing is absolutely necessary, it was the opinion of the framework designers that given the constraints of the language that composition via delegation was the best design choice they could make. After working in it for around a year I'm inclined to agree that there choice was a good one. But it was a little odd for me when I first came to Cocoa from other languages.
Bryan McLemore
+4  A: 

With delegates, you can have one object be the delegate of many other objects. For example, you can have your MyController instance be the delegate of an NSTableView, an NSTextField, an NSWindow, and any other objects that compose your interface. This gives a compact place to put all of your user interface code related to one section of your UI.

If you'd done that with subclassing, you'd have to create one subclass every object you wanted callbacks from.

Also, this is a classic inheritance vs composition question

Jon Hess
I suppose this really is just the inheritance vs composition problem
Casebash
Good point about writing one controller for multiple objects in your interface
Casebash