Principle of Delegation, what is it?

8

What does Delegation Principle mean in Object Oriented Programming?

After some research, I found a definition of this principle:

  

Delegation Principle: way to make composition as powerful for reuse as inheritance.

I found an example code in Java:

public abstract class Pato {

    public Padrao_Voaveis m_Padrao_Voaveis;

    public Pato(){

    }

    public void finalize() throws Throwable {

    }

    public void comportamento_pato(){

        m_Padrao_Voaveis.voar ();
        //(delega para a classe de comportamento)
    }

    public abstract void mostrar();

    public void nadar(){

    }
}

But I could not understand this principle. Does anyone have a better way to explain myself?

    
asked by anonymous 17.09.2015 / 20:09

4 answers

7

This is another mechanism for code reuse. Usually it is used in languages that do not use the concepts of classes (Actor and Self). In these languages objects are called prototypes and each of them implements a specific behavior.

If object A does not implement a particular message it delegates (relays) the message to object B. If object B implements that message then it runs it with the data of A, otherwise it delegates it to its "delegates".

In class-based languages this mechanism can also be obtained. This is done through the message to the other object. This is for necessary that the delegating object of the service contain a reference to the responsible object by execution.

It is important to note that delegation differs from inheritance in two important ways:

  • With inheritance, you have only one instance of the object. There is only one indivisible object, because what is inherited becomes an intrinsic part of the new class.

  • Delegation usually provides the user with only what is on the public interface. Normal inheritance gives more access to the inherited class's inner details.

  • Ifyoulookcarefullyatthepreviousfigure,youwillnoticethatRoboVulcaostillhas3methodsrelatedtothesensor;thesearemethodsthatonlycallthecorrespondingsensormethods.Thisisexactlywhatdelegationis,justpassingfunctionalitytothecontainedparts.

    Delegationcomeswithcompositiontoprovideflexibleandelegantsolutionsliketheonewehaveseenpreviously,andalsorespectstheprincipleof"separating mutable code from static code", but also charges a price for it: the need for methods that "wrap" calls require extra processing time because of calls to those methods.

        
    17.09.2015 / 20:21
    5

    The term can be used in different ways in programming. In OOP it's basically a more specific form of aggregation . You leave certain aspects to another class - the delegate - to accomplish what this class - the delegate - needs.

    Delegation occurs by having a reference in some member to the other class. It allows you to reuse code manually.

    Delegation does not automatically occur with inheritance and polymorphism , but in this case the term does not usually be used.

    Only inheritance can be problematic in some cases. And look at that I'm talking about the multiple inheritance that is even more problematic and many languages do not implement it.

    Inheritance is often abused and one thinks of reusing the code without correctly conceptualizing the relationship between the more general and 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 did not even have inheritance. This may require a bit more code in some cases by requiring manual delegation, which is what we are talking about here, but they make the language simpler and avoid certain types of problems.

    Your example

    In your example it shows what I I commented on the previous question . For this class it does not matter how the flight takes place. It is not her responsibility (remembering that classes must have single responsibility, be cohesive ). He takes care of the duck in a general way. The specific flight mechanism is defined in another class. Your class just calls this mechanism.

    If it were not for this delegation, besides the class doing more than it needs, it would still have to play 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 specific type of this variable has not been defined in this code, so you can use a subtype of Padrao_Voaveis giving some flexibility to what will actually be executed depending of how this variable is initialized, which can occur within the class itself in configurable or non-configurable form, or externally, that is, a dependency injection .

    This can be especially useful when using interfaces. Let's say that the comportamento_pato() method is part of an interface that you must implement in this class. Give work, take risks writing all the code of this method. But you can have the specific implementation in another class. So you fulfill the contract by defining the method required by the interface but delegate the implementation of the code to what the other class already knows how to do.

    Some languages have facilities that automate this delegation a little.

        
    17.09.2015 / 20:21
    3
      

    In Object Oriented Programming, according to Angun Croll, engineer and   author of the JavaScript blog, defines the Delegation as a technique   which promotes code reuse by allowing invocation of the function   implementation in the context of a specific instance -   regardless of the hierarchical line of the instance and function. - source

    Here's an example:

    private static function curlExec($link, $data) {
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $link);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data, '', '&'));
    
        $response = curl_exec($ch);
    
        echo $response;
    }
    

    And being called in another function ...

    public function login($email, $senha) {  
    
        $data = array(
            'nome' => $email,
            'senha' => $senha
        );
    
        $link = 'http://teste.local/login';
        $response = self::curlExec($link, $data);
    
        ....      
    
        
    17.09.2015 / 20:21
    0

    Delegation in the Object Oriented view is when you develop an Object that delegates tasks to other objects, it's as if you had an intermediate object between SuperClass and the Class that has processing.

    In this article you can find more details on this subject

        
    17.09.2015 / 20:23