Return on methods

4

Colleagues.

I have a class where my methods that contain arguments, but have no return, I usually put the following code at the end:

public function metodoRetorno($valor) {
    // ...
    return true;
}

But in methods that do not have (void) arguments eg:

public function metodoVazio() {
    // ...
}

... I do not put any kind of feedback. Some time ago, if I'm not mistaken, I learned that it is advisable to put the return as true, but I can not remember if methods that have no arguments use this.

Is this logic correct?

    
asked by anonymous 08.11.2015 / 14:53

3 answers

4

Parameters are one thing and return is something else.

Imagine that each method represents a work to be done. The parameters are what is required for the work to be performed (in addition to what is already available through $this ). Return is the result that the method gives to the caller.

To illustrate this in a very simple and didactic way, imagine some problems:

  • You go to the bakery to buy bread. When you arrive at the bakery, here's what you need:

    • Know the number of breads you are going to buy.

    • Have money or card or check or some other means of payment.

    And here's what you get as a result:

    • A bag of breads.

    In this way, let's assume that I have modeled the function comprarPaes :

    public function comprarPaes($numeroDePaes, $meioDePagamento) {
        // ...
        return $sacola;
    }
    

    That is, this function has two parameters and has a return.

  • You're going to take the garbage out. Here's what you need:

    • Find out where the rubbish is.

    • Know where the bin is.

    I could model this function more or less like this:

    public function botarLixoPraFora($lixo, $lixeira) {
        $lixo->embalar();
        sairParaRua();
        $lixeira->colocarLixo($lixo);
    }
    

    And notice that this function, despite having two parameters, has no return. It simply performs a task and once it is done, no special result is needed beyond the execution of the task itself.

  • The dollar is very unstable in the last few days and you want to know the quote today:

    public function buscarCotacaoDoDolar() {
        // ...
        return $cotacao;
    }
    

    And this function, although it has no parameters, has a return type.

  • You'll turn on the radio to listen to music:

    public function ouvirMusica() {
        $radio = localizarRadio();
        $radio->ligar();
        $radio->sintonizarAondeTemUmaMusicaLegal();
    }
    

    And this function has no parameters and no return type. It consists of a task to be done where nothing needs to be returned, no special data (parameter) is required to execute the task, and no special result is needed beyond the execution of the task itself.

  • Finally, look at the four combinations we have, all perfectly valid:

    • With parameters and with return.
    • With parameters and no return.
    • No parameters and return.
    • No parameters and no return.

    That is, there is no rule that says that if there is no return then it should not have parameters or the opposite.

    When a function can not perform the task at hand, or fails to execute it, the appropriate mechanism to use is the handling of exceptions. For example:

    public function comprarPaes($numeroDePaes, $meioDePagamento) {
        $padaria = irAPadaria();
        if (!$padaria->estaAberta()) {
            throw new Exception("A padaria não está aberta. Não dá para comprar pão.");
        }
        $padaria->irAteOBalcao();
        $atendente = $padaria->esperarAtendente();
        $atendente->pedirPaes($numeroDePaes);
        try {
            $atendente->realizarPagamento($meioDePagamento);
        } catch (Exception $e) {
            // Ocorreu um erro com o pagamento.
            // Pode ser que não tenha dinheiro suficiente
            // ou o cartão pode estar fora da validade,
            // ou algum outro problema desse tipo.
            throw new Exception("Problema no pagamento: " . $e->getMessage());
        }
        $sacola = $atendente->receberSacola();
        return $sacola;
    }
    

    In this case, note that at points where something goes wrong that makes it impossible for the task to be completed, an exception is thrown. It is not good to return true if it worked and false if it did not, as this tends to be confusing and the idea of exception handling came up exactly so that you do not have to do this sort of thing. In addition, the exception may carry much more information about the error than a simple true or false .

    Note also that the function comprarPaes has return and parameters, and within it is used realizarPagamento that has parameter but has no return, esperarAtendente that has return and has no parameters and irAteOBalcao it has neither return nor parameters. Anyway, we can use the four possible combinations together with exception handling.

        
    08.11.2015 / 19:30
    3

    Method or function arguments do not define or determine the return type.

    Functions and methods that do not have a return are called "null return" or "void return" functions.

    Example

    function Foo(){
        $r = 1 + 1;
    }
    

    This function does not have a return. So, what the function returns is NULL , because in PHP, an undefined return is returned as NULL : link

    In PHPDocs or PHP-Fig, there are no specifications that "enforce" the return definition. Maybe because PHP already automatically returns as null when there is no definition.

    Also note that even invoking echo or print , without setting return , the func- tion will still return as NULL .

    function Foo(){
        $r = 1 + 1;
        echo 'a';
    }
    
    var_dump(Foo());
    
        
    08.11.2015 / 20:53
    2

    There should be no relationship between the arguments that the method accepts, and the return it should pass.

    If a method does not return any value, its return is understood as void (empty).

    Generally we should return booleans ( true or false ) in methods that execute some block of code, in which case the boolean would serve to give a feedback in relation to what was done in the method (for example, whether the code was successfully executed or not).

    In relation to not returning anything in functions that do not accept arguments, I think this makes even some sense in class methods that "prepare" the properties for some later method (for example, constructors). It may also make sense in methods that are part of some design pattern (for example, the template method ) but again I think it depends a lot on a case by case basis. p>     

    08.11.2015 / 15:01