php – Return on methods

Question:

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 (empty) arguments eg:

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

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

Is this logic correct?

Answer:

Parameters are one thing and return is another thing.

Imagine that each method represents a job to be done. Parameters are what is needed for the work to be done (in addition to what is already available through $this ). The return is the result that the method gives to the caller.

To exemplify 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 buns you are going to buy.

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

    And here's what you bring as a result:

    • A bag of bread.

    In this way, let's suppose that I model the comprarPaes function:

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

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


  1. You're going to take out the trash. Here's what you need:

    • Know where the trash is.

    • Know where the dump is.

    I could model this function something 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 performs a task and once it is done, no special results are needed other than the execution of the task itself.


  1. The dollar has been very unstable in recent days and you want to know today's rate:

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

    And this function, although it doesn't have any parameters, has a return type.


  1. You will 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 needed to perform the task, and no special results are needed other than the execution of the task itself.


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

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

In other words, there is no rule that says that if there is no return then it must not have parameters or the opposite.

When a function cannot perform the task at hand, or fails to do so, the proper 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's not good to return true if it worked and false if it didn't, as this tends to be confusing and the idea of ​​handling exceptions came up just so that you don't need to do this sort of thing. Also, the exception can carry much more information about the error than a simple true or false .

Also note that the function comprarPaes has return and parameters, and inside it is used to realizarPagamento having parameter but does not return, the esperarAtendente that has return and has no parameters and irAteOBalcao which has neither return nor parameters. Anyway, we can use the four possible combinations together with exception handling.

Scroll to Top