The term can be used in different ways in programming. In OOP it is basically a form of aggregation more specific. You leave certain aspects for another class - the delegate - to accomplish what this class - the delegator - needs.
Delegation occurs by having a reference in some member to the other class. It allows code reuse manually.
The delegation does not fail to occur automatically with inheritance and polymorphism, but in this case the term is not usually used.
Only inheritance can be problematic in some cases. And I’m talking about multiple inheritance which is even more problematic and many languages don’t even implement it.
Inheritance is often abused and the reuse of the code is considered without properly conceptualizing the relationship between the more general and more specific type. Often reuse can be obtained without inheritance. Of course this will have to be done more manually. On the other hand there is more control and flexibility over reuse.
In fact modern languages preferred not to have an inheritance. This may require a little more code in some cases by requiring manual delegation, which is what we’re talking about here, but they make language simpler and avoid certain kinds of problems.
Your example
In your example shows what I I commented on a previous question. For this class it does not matter how the flight takes place. It is not her responsibility (remembering that the classes must have single responsibility, being cohesive). It takes care of the duck in a general way. The flight-specific mechanism is defined in another class. Its class only calls this mechanism.
If it wasn’t for this delegation, in addition to the class being doing more than it needs, it would still have to reproduce a code, which you may not even have access to, in your method. To access the method that actually implements the mechanism you need to have a reference to this class and this is obtained with the variable m_Padrao_Voaveis
.
An interesting detail is that the type specific of this variable was not defined in this code and therefore you can use a sub-type of Padrao_Voaveis
giving some flexibility to what will actually be executed, depending on how this variable is initialized, which may occur within the class itself in configurable or not, or externally, i.e. dependency injection.
This can be especially useful when using interfaces. Let’s say the method comportamento_pato()
is part of an interface that you must implement in this class. It takes work, you take risks writing all the code of this method. But you can have the specific implementation in another class. Then you fulfill the contract by defining the method required by the interface but delegate the implementation of its code to what the other class already knows how to do.
Some languages have facilities that automates a little this delegation.
Polymorphism this?
– rray