It is good practice to use 'return' functions or 'void' methods

12

Question taken to answer a comment , so that it can be better understood, and because I think it can be an interesting and useful question for other users who may wonder the same thing.

Regarding the returns I know that being void functions do not return any value, even so a teacher told me that as a good practice she will always use them - Manuel Aviles

    
asked by Angel Angel 13.05.2017 в 22:47
source

5 answers

19
  

Regarding the returns I know that being void functions do not return any value, even so a teacher told me that as a good practice she will always use them - Manuel Aviles

An important distinction.

It does not matter if a function returns a value or does not return it, an instruction return will behave in the same way in both cases: it will exit the running function. The only difference will be that, together with the instruction return , a value will be returned (or not).

Early exit of the function.

It is considered early exit of a function to leave without having reached the end of the function, this is done using the return instruction, which creates new exit points of the function to the end of the function.

Like many other programming topics, the single exit principle 1 is misinterpreted or decontextualized or abused.

There is nothing wrong with leaving a function with a return instruction in any part of a function (whether the function returns something or not).

The mechanisms of the language when leaving a function are the same whether it comes out early or leaves the function, the only possible difference would be that certain instructions would not be executed (thus avoiding their side effects ) but it would happen exactly the same with a if instruction.

Multiple function outputs What is the problem?

If there is nothing wrong with it, what is the problem? It is not a performance problem, but a design problem, sometimes having several exit points of a function (whether it returns something or not) makes it more difficult to follow the logic of the function and consequently it will be more difficult to debug and work with it, some programmers defend the principle of single exit 1 for this reason.

Other programmers defend the single exit principle 1 for performance, but there will be no performance difference between following or not following this principle nor or in java (or in any modern programming language) so defending that position is just a misinterpretation of the principle.

Are you sure there's no problem?

We can find problems with multiple exit points in a function (early function exits) in or or since in these languages this type of practice is prone to errors (they do not follow the recommendations of Edsger W. Dijkstra on structured programming) by making it possible for some variables to be uninitialized or for a certain code crucial does not run; but it is due to particularities of these languages, modern languages do not have these problems.

Structure the code.

When you have a long function that can exit at several points (returning or without returning value) we can structure it as the Acueducto de Amoreira 2 or as the Temple cursed 2 :

Acueducto Amoreira
if (condicion_1)
{
    // hacer cosas 1
    if (condicion_2)
    {
        // hacer cosas 2
        if (condicion_3)
        {
            // hacer cosas 3
            if (condicion_4)
            {
                // hacer cosas 4
                if (condicion_5)
                {
                    // hacer cosas 5
                    // ...
                }
                else
                {
                    // Otras cosas
                }
            }
            else
            {
                // Otras cosas
            }
        }
        else
        {
            // Otras cosas
        }
    }
    else
    {
        // Otras cosas
    }
}
else
{
    // Otras cosas
}
Templo Maldito
if (!condicion_1)
{
    // Otras cosas, como salir de la función
    return;
}
// hacer cosas 1

if (condicion_2)
{
    // Otras cosas, como salir de la función
    return;
}
// hacer cosas 2

if (condicion_3)
{
    // Otras cosas, como salir de la función
    return;
}
// hacer cosas 3

if (condicion_4)
{
    // Otras cosas, como salir de la función
    return;
}
// hacer cosas 4

if (condicion_5)
{
    // Otras cosas, como salir de la función
    return;
}
// hacer cosas 5

In the Amoreira Aqueduct the code ripples through multiple indentations (making it look like an aqueduct) and the function flows at the end without going through instructions return , there is a single point of entry and exit. In The Cursed Temple, the function passes different tests and if it does not exceed them, it comes out with a return instruction, there is an entry point and several exits.

Neither of the two structures is better than the other, but, according to the tastes of the programmer: one will be easier to use than the other.

1 I have just coined the name, I do not know that the practice of having only one exit point in a function is officially known.

2 I have just coined the name, I am not aware that this structure receives this name.

    
answered by 15.05.2017 в 10:47
4

First of all, I am nobody to judge a teacher, because that is a teacher and only he will know why of this recommendation. It could be a methodology for for example:

  • You get used to putting return on the functions and do not forget to avoid compilation errors, while "you learn".

  • Maybe I'll do it to explain other things later on.

  • Or for anything else.

That said in my opinion as you have it or for a similar function apart from being confusing, because you can think that the type of return is forgotten and the signature of the function is wrong or anything else, example of where you use it "or for similar cases":

void resetboard(char numeros[3][3])
{   
    for (int i=0;i<3;i++)
    {
        for (int j=0;j<3;j++)
        {
           //..  
return;    
}

In the previous case or similar in my point of view does not serve as "nothing".

Now there are some cases in which if it is useful, to make more efficient a function with many if - else using a pattern that I remember to remember is called "gorilla pattern", in which if it is useful under my point of seen, let's take this example:

let's say that the function reset can receive any integer as it is not controlled previously in the call to the function

void reset(in numero)
{   
    if (numeros == 1)
    {

    }
    else if (numeros == 2)
    {

    }
    else if (numeros == 3)
    {

    }
    else if (numeros == 4)
    {

    }
    else if (numeros == 5)
    {

    }
    else if (numeros == 6)
    {

    }
    else if (numeros == 7)
    {

    }
    else if (numeros == 8)
    {

    }
    else if (numeros == 9)
    {

    }  
}

As you can see the above, go through the if until you find a valid one. With what you have to go through all the if - else, and that function can be called with any int, so that of all the values that can have an int only 9 are accepted.

Now with the use of 'return' you can make that function more efficient without having to go through all the if - else for an int that is not accepted:

void reset(in numero)
{   
    if (numeros < 1 || numeros > 9)
    {
        return;
    }
    else if (numeros == 1)
    {

    }
    else if (numeros == 2)
    {

    }
    else if (numeros == 3)
    {

    }
    //..
}

Now with this part:

    if (numeros < 1 || numeros > 9)
    {
        return;
    }

check that the number is within the range in which actions are performed, otherwise, we leave the function, so we avoid wasting time in checking all the if - else, and if that function is called many times as it can be in the update of a game, because in this case it is very useful, not to consume resources in that function more than necessary.

    
answered by 13.05.2017 в 22:47
1

A tip, while you are a student of that teacher, use the returns in all the code that has to be seen by that teacher, especially in an exam.

As for the real world ...
The general tendency is to make languages as non-verbose as possible. For example, in a modern language with Scala not only can you do without a return in a void function, you can also do without a function that returns something. This would be the code (procedural style) in Scala to add from 1 to 10:

def sumar = {
  var suma = 0
  for ( i <- 1 to 10 ) {
    suma += i
  }
  suma // Esta línea hace lo mismo que: return suma
}

In C ++ this is not possible. You'll have to put return suma at the end of a function that returns an integer. But you can omit it in a void function. And the advisable thing is to omit it. The key that closes the function is already telling you that the function ends, you do not need to write it twice.

Flour of another costal is to put a return in the middle of a function in a conditional sentence so that the function finishes prematurely. There it makes sense to do it.

    
answered by 13.05.2017 в 23:34
1

Each teacher, actually each person, has different ways of programming. Some prefer:

main()
{
  int numero;
  printf("Ingrese un numero");
  scanf("%d", &numero);
}

others:

main()
{
  int numero;
  numero = ingresar_numero();
}

others:

main()
{
  int numero;
  ingresar_numero(&numero);
}

Although there are 3 simple examples, there are 3 different ways of for example entering a number in the first case the logic is included in the main, in the second case the logic is included in the function and it returns the result, and in the third case the logic is included in the function and does not return anything, since it writes in memory.

Personally, I prefer that the functions return "something" even if it is a bool variable that indicates whether the operation was performed correctly under any established criteria. Greetings.

    
answered by 29.08.2017 в 04:12
0

Not really, it only forces you to have an exit, since it would be a simple return and since it is a void method it does not have the slightest case. It is only a practice by constumbre, many languages of current generation like Ruby avoid the use of this word since it only returns the last evaluated element, the return is very verbose.

    
answered by 13.07.2018 в 23:20