Why we should always return values from a function?

11,572

Solution 1

A function needn't return anything... If you look at C(++) function, many of them don't (well, not explicitly):

void nonReturningFunction(const int *someParam);
int main()
{
    int i = 12;
    nonReturningFunction(&i);
    return 0;
}
void nonReturningFunction(const int *someParam)
{
    printf("I print the value of a parameter: %d",someParam);
}

The latter returns nothing, well, it returns a void. The main function does return something: 0, this is generally a signal to the system to let it know the programme is finished, and it finished well.

The same logic applies to PHP, or any other programming language. Some functions' return value is relevant, another function may not be required to return anything. In general functions return values because they are relevant to the flow of your programme.

Take a class, for example:

<?php
    class Foo
    {
        private $foo,$bar;
        public function __construct()
        {
            $this->foo = 'bar';
        }
        public function getFoo()
        {
            return $this->foo;//<-- getter for private variable
        }
        public function getBar()
        {
            return $this->foo;//<-- getter for private variable
        }
        public function setBar($val = null)
        {
            $this->bar = $val;
            return $this;//<-- return instance for fluent interfacing
        }
        public function setFoo($val = null)
        {
            $this->foo = $val;
            return $this;
        }
    }
    $f = new Foo();
    $f->setFoo('foo')->setBar('bar');//<-- fluent interface
    echo $f->getFoo();
?>

If the setter function didn't return anything, you'd have to write:

$f->setFoo('foo');
$f->setBar('Bar');

So in this case, return values are relevant. Another example where they're irrelevant:

function manipulateArray(array &$arr)//<-- pass by reference
{
    sort($arr);
}
$arr = range('Z','A');
manipulateArray($arr);
var_dump($arr);//array is sorted

as opposed to:

function manipulateArray(array $arr)//<-- pass by copy
{
    sort($arr);
    return $arr;
}
$arr = range('Z','A');
manipulateArray($arr);
var_dump($arr);//array is not sorted!
$arr = manipulateArray($arr);//<-- requires reassign

Passing by reference is deemed risky in many cases, that's why the latter approach is generally considered to be better. So in many cases the functions needn't return a value, but they do all the same because it makes the code safer overall.
That might be why you're under the impression that functions must always return a value.

Solution 2

This is the heritage of old programming. In older languages like Fortran you always had to return with something with a type i.e. int, float, bool etc. Since C you can return with a "void" type, and that's the default in most C functions if you don't specify a return statement, it returns with void at the end. In Java for example you have to specify a return type and then return with that type. If you don't want to return anything, you use the 'void' type:

//This works
public void boo() {
   return;
}


//This gets you an error
public int boo() {
   return;
}

//This gets you an error too, because you must specify a type for any function in Java
public boo() {
   return;
}

So it's more like what Lix said, if you have something to return with, you do. In most functional programs your functions can return either with data, or true/false marking success or failure. In many systems a function can return an int indicating success or failure like '1' or '-1'. Unix shell programs use this.

In other languages like PHP you don't need to return anything, but in the background PHP still attaches a 'void' type as returned value to your function, you just don't have to explicitly write it.

Hope this helps

Solution 3

This is done so that there is a definitive ending point for the function. It is mainly to increase readability and to help future programmers to understand what you were trying to do.

There should be no assumption about what a function returns.

Solution 4

There is so many reasons...

That's better for your architecture : a function takes parameters, work with them and returns expected result. In such way you may be able to reuse it and to arrange your code.

That's better for unit testing, you can very easily check if your function return expected result.

Solution 5

Generally speaking in computer programming a function is a reusable unit of code that takes some input (including nothing) and returns a value.

Some languages have similar constructs to functions called procedures and these are reusable pieces of code that take some input (including nothing) and perform some activity but don't return a result.

However some languages may not have the latter as a syntactical construct and mey use functions to implement procedures. So you here you get functions where you ignore the result. Also some languages may not have an requirement to actually force the code to return something from a function (i.e. they implement procedures using functions).

So if you have only the latter as your option, then you could argue like @lix that it's good practise to return things from function. The primary reason is that though the function can be used like a procedure - the caller may call it like function and expect to work with the result. Remember that test code is a primary use case and it might be the only reason for following this convention.

Personally I think convention is the answer. Do whatever works best for you, but try to always do the same, and if you need to diverge - find ways to let the user know.

Share:
11,572
Yousuf Memon
Author by

Yousuf Memon

.__.

Updated on June 23, 2022

Comments

  • Yousuf Memon
    Yousuf Memon almost 2 years

    I am not a big programming guy but have listen from programmers a lot of times that we should always return values from a function. I want to know the reason.