I'm reading Joshua Bloch's Effective Java and getting quite a lot of it. The book is a catalogue of numbered items of advice, some standard, some controversial, with fairly detailed exposition on each.
Item 14: Favor composition over inheritance is uncontroversial, being a restatement of the second principle of object-oriented design in Design Patterns, the famous Gang of Four book by Gamma and company. However, in his discussion, Bloch writes that
Sometimes the combination of composition and forwarding is erroneously known as delegation. Technically, it's not delegation unless the wrapper object passes itself to the wrapped object [Gamma95, p. 20].
I think Bloch misread page 20 and, thanks to the reference, I was able look at page 20 over his shoulder:
Delegation is a way of making composition as powerful for reuse as inheritance [...] [W]ith inheritance, an inherited operation can always refer to the receiving object through the this
member in C++ [...]. To achieve the same effect with delegation, the receiver passes itself to the delegate to let the delegated operation refer to the receiver.
This text is suggestive, however the example that follows makes no attempt to achieve the this
effect. In the example, Window
object delegates an Area()
operation to a Rectangle
object. The Window
object does not pass itself to the Rectangle
.
In the Glossary of the GoF book, on page 360, there is another definition of delegation: An implementation mechanism in which an object forwards or delegates a request to another object. The delegate carries out the request on behalf of the original object.
I haven't edited anything out this time.
I think Bloch took something optional and made it an essential part of the definition of delegation. The paragraph I quoted from the GoF is a little ambiguous, but the rest of the book seems clear: it is still delegation even if the delegating object does not pass itself as part of the request to its delegate.
To be sure, this is a detail of no importance. The definition of delegation doesn't really depend on the GoF. My quibble hardly affects my opinion of Effective Java: it's still a book I'm glad I bought. It's just a case where the reference doesn't give support to the author the way it appears to.