Thursday, 12 February 2009

Delegation : a powerful concept

Delegation is an important OO concept, and is used a lot in the Cocoa framework. With the usage of delegation the developers of the framework gives the capability to other programmers to interfere with the execution of the code.

For example : in NSWindow you can set a delegate (via setDelegate:). Now when a window will close , the NSWindow object will send the message windowWillClose: to the delegate.
The delegate can now do some cleanup before the window actually closes.

With delegation you also avoid the need for subclassing ; this can be an advantage but sometimes a disadvantage.
The advantage is that you don't need to interfere with a whole class library (try to subclass NSWindow , you'll see that its hard work to get the subclass working properly).
The disadvantage of delegation is that the framework developer decides on the 'plug' points, if for example the windowWillClose: method was not delegated then you couldn't do anything before a window close and then the only option you have is to subclass and override the method.

Another example fo delegation is in the case of board game with different pieces that moves around. In this case you have for example a class Board and several classes of Pieces.
If we want to implement a method that tests if pieces are colliding or reaching the boundaries of the board we can do 2 things :

1. We can implement all logic in the Board class, the disadvantage here is that the class Board 'knows' the internal setup of all pieces.
And so it means that if we add a new piece, we have to change the method also

2. We can use the principles of delegation and delegate the test of colliding to each piece itsself (via method call like [aPiece hasCollidedOn: self] , where self is the board).
This has the advantage that each piece can implement the test like he wants , and because we pass the board as a parameter; the piece can still interrogate the board.

Later on I'll publish my implementation of tetris where I've implemented this type of delegation

No comments:

Post a Comment