Return in methods

Asked

Viewed 315 times

4

Colleagues.

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

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

But in methods that have no ( empty ) arguments.:

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

... I don’t put any returns. Some time ago, if I am not mistaken, I learned that it is advisable to put the return as true, but I cannot remember if methods that have no arguments use this.

This logic is correct?

  • Thank you all for your explanations.

3 answers

4

The parameters are one thing and the return is something else.

Imagine that each method represents a work to be accomplished. The parameters are what is necessary for the work to be done (beyond what is already available through the $this). The return is the result that the method gives to those who called it.

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


  1. 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 will buy.

    • Having cash or card or check or some other means of payment.

    And here’s what you bring as a result:

    • A bag of bread.

    So let’s assume that I modeled the function comprarPaes:

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

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


  1. You will take out the trash. Here’s what you need:

    • Knowing where the garbage 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 note that this function, despite having two parameters, has no return. It simply executes a task and once ready, no special result is needed other than the execution of the task itself.


  1. The dollar is very unstable in the last days and you want to know today’s quote:

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

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


  1. You’ll turn on the radio to listen to music:

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

    And this function, it 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 needed to perform the task and no special result is needed beyond the execution of the task itself.


Anyway, note 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 there should be no parameters and neither the other way around.

When a function cannot perform the task available, or fails to perform it, the appropriate mechanism to use is exception handling. 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 whether it worked and false if it did not, because this tends to be confusing and the idea of treating exceptions has arisen exactly so that it is not necessary to do this kind of thing. In addition, the exception can 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 the realizarPagamento which has parameter but has no return, to esperarAtendente that has return and has no parameters and the irAteOBalcao that has neither return nor parameters. Finally, we can use the four possible combinations together with the treatment of exceptions.

3

Arguments of methods or functions do not define or determine the return type.

Non-return functions and methods are called "null return" or "void Return".

Example

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

This function does not have a return. Therefore, what the function returns is a NULL, because in PHP, an undefined return is returned as NULL: http://php.net/manual/en/functions.returning-values.php

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

See also that even invoking echo or print, without defining the return, the function will still return as NULL.

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

var_dump(Foo());

2

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

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

Usually we should return boolean (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).

Regarding not returning anything in functions that do not accept arguments, I think it makes sense in class methods that "prepare" properties for some later method (e.g., constructors). It may also make sense in methods that are part of some Pattern design (for example, the method template) but, again, I think it depends a lot on case by case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.