为什么我们总是要返回函数的值?

时间:2022-09-11 19:12:58

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.

我不是一个大型编程人员,但是从程序员那里听了很多遍,我们应该总是从函数返回值。我想知道原因。

7 个解决方案

#1


6  

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

函数不需要返回任何东西……如果你看看C(++ +)函数,它们中的很多都不是(嗯,不是显式的):

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.

后者不返回任何东西,它返回一个空。主函数确实返回一些东西:0,这通常是一个信号,让系统知道程序已经完成,并且它已经完成了。

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.

同样的逻辑适用于PHP或任何其他编程语言。一些函数的返回值是相关的,另一个函数可能不需要返回任何东西。通常函数返回值,因为它们与程序的流相关。

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:

如果setter函数没有返回任何内容,则必须写:

$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.

在许多情况下,通过引用传递被认为是有风险的,这就是为什么后者通常被认为是更好的方法。所以在很多情况下,函数不需要返回值,但是它们都是一样的,因为它使代码整体上更安全。这可能就是为什么您认为函数必须总是返回一个值。

#2


7  

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:

这是旧程序设计的传统。在旧的Fortran等语言你总是不得不返回的东西即int型,浮点数、保龄球等等。因为C可以返回一个“空白”类型,默认在大多数C函数如果你不指定返回语句,它返回与空虚。例如,在Java中,您必须指定返回类型,然后使用该类型返回。如果您不想返回任何东西,您可以使用“void”类型:

//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.

这更像是Lix说的,如果你有东西要返回,你就去做。在大多数函数程序中,函数可以返回数据,也可以返回真/假标记成功或失败。在许多系统中,函数可以返回一个int数,表示成功或失败,如“1”或“-1”。Unix shell程序使用这个。

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.

在PHP等其他语言中,您不需要返回任何东西,但是在后台PHP中,PHP仍然将“void”类型作为返回值附加到函数中,您不必显式地编写它。

Hope this helps

希望这有助于

#3


6  

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.

对于函数返回的内容不应该有任何假设。

#4


5  

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.

这对于单元测试来说更好,您可以很容易地检查函数是否返回预期结果。

#5


3  

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.

有些语言对称为过程的函数有类似的构造,这些是可重用的代码片段,它们接受一些输入(包括nothing)并执行一些活动,但不返回结果。

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).

然而,有些语言可能不会将后者作为语法结构和mey使用函数来实现过程。你得到了忽略结果的函数。另外,有些语言可能不需要强制代码从函数中返回一些东西(例如,它们使用函数实现过程)。

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.

因此,如果你只有后者作为你的选择,那么你可以像@lix那样争辩说从函数返回东西是很好的做法。最主要的原因是,虽然函数可以像过程一样使用——调用者可以像函数一样调用它,并期望得到结果。请记住,测试代码是一个主要的用例,它可能是遵循此约定的唯一原因。

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.

我个人认为习惯是答案。做对你最有效的事,但也要尽量做同样的事,如果你有分歧的话——想办法让用户知道。

#6


2  

Also: flexibility. Consider echoing vs returning from inside a function. With, say, a returned true or false from a function, you can modify how things are displayed in views in as many ways as you want. Having a string echoed doesn't give you this flexibility.

另外:灵活性。考虑从函数内部返回的回声。对于从函数返回的true或false,您可以根据需要以多种方式修改视图中显示的内容。有一个字符串回显不会给你这种灵活性。

#7


0  

Some earlier languages had procedures and functions. Procedures returned nothing (they just did something). Functions returned something. I guess someone decided it was unnecessary to have both since a function could simply be void (as used in C). I just wrote a quick function to store data in the database. Since the data was filtered in several levels the odds of an error was negligible, nonetheless, I included in the function an alert, that would echo on an error, so returning even an error alert wasn't necessary. (This is an in-house site, that wouldn't be for public use) so having the function return anything was completely unnecessary.

一些早期的语言有程序和功能。程序什么也没有返回(它们只是做了一些事情)。函数返回。我猜有人认为没有必要同时使用这两个函数,因为一个函数可以是空的(如C中使用的)。由于数据是在几个级别进行过滤的,所以出现错误的几率是可以忽略不计的,不过,我在函数中加入了一个警告,它会对错误进行响应,因此即使返回一个错误警报也是不必要的。(这是一个内部站点,不会用于公共用途)所以让函数返回任何东西是完全不必要的。

Since the question was why we should ALWAYs return a value, it's not about why it's sometimes good to return a value, but what reason exists to demand we should always return a value, and there is no valid reason to ALWAYs return a value from a function.

既然问题是为什么我们总是要返回一个值,这不是为什么返回一个值有时是好的,而是有什么原因需要我们总是返回一个值,并且没有任何正当的理由总是返回一个函数的值。

#1


6  

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

函数不需要返回任何东西……如果你看看C(++ +)函数,它们中的很多都不是(嗯,不是显式的):

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.

后者不返回任何东西,它返回一个空。主函数确实返回一些东西:0,这通常是一个信号,让系统知道程序已经完成,并且它已经完成了。

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.

同样的逻辑适用于PHP或任何其他编程语言。一些函数的返回值是相关的,另一个函数可能不需要返回任何东西。通常函数返回值,因为它们与程序的流相关。

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:

如果setter函数没有返回任何内容,则必须写:

$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.

在许多情况下,通过引用传递被认为是有风险的,这就是为什么后者通常被认为是更好的方法。所以在很多情况下,函数不需要返回值,但是它们都是一样的,因为它使代码整体上更安全。这可能就是为什么您认为函数必须总是返回一个值。

#2


7  

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:

这是旧程序设计的传统。在旧的Fortran等语言你总是不得不返回的东西即int型,浮点数、保龄球等等。因为C可以返回一个“空白”类型,默认在大多数C函数如果你不指定返回语句,它返回与空虚。例如,在Java中,您必须指定返回类型,然后使用该类型返回。如果您不想返回任何东西,您可以使用“void”类型:

//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.

这更像是Lix说的,如果你有东西要返回,你就去做。在大多数函数程序中,函数可以返回数据,也可以返回真/假标记成功或失败。在许多系统中,函数可以返回一个int数,表示成功或失败,如“1”或“-1”。Unix shell程序使用这个。

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.

在PHP等其他语言中,您不需要返回任何东西,但是在后台PHP中,PHP仍然将“void”类型作为返回值附加到函数中,您不必显式地编写它。

Hope this helps

希望这有助于

#3


6  

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.

对于函数返回的内容不应该有任何假设。

#4


5  

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.

这对于单元测试来说更好,您可以很容易地检查函数是否返回预期结果。

#5


3  

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.

有些语言对称为过程的函数有类似的构造,这些是可重用的代码片段,它们接受一些输入(包括nothing)并执行一些活动,但不返回结果。

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).

然而,有些语言可能不会将后者作为语法结构和mey使用函数来实现过程。你得到了忽略结果的函数。另外,有些语言可能不需要强制代码从函数中返回一些东西(例如,它们使用函数实现过程)。

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.

因此,如果你只有后者作为你的选择,那么你可以像@lix那样争辩说从函数返回东西是很好的做法。最主要的原因是,虽然函数可以像过程一样使用——调用者可以像函数一样调用它,并期望得到结果。请记住,测试代码是一个主要的用例,它可能是遵循此约定的唯一原因。

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.

我个人认为习惯是答案。做对你最有效的事,但也要尽量做同样的事,如果你有分歧的话——想办法让用户知道。

#6


2  

Also: flexibility. Consider echoing vs returning from inside a function. With, say, a returned true or false from a function, you can modify how things are displayed in views in as many ways as you want. Having a string echoed doesn't give you this flexibility.

另外:灵活性。考虑从函数内部返回的回声。对于从函数返回的true或false,您可以根据需要以多种方式修改视图中显示的内容。有一个字符串回显不会给你这种灵活性。

#7


0  

Some earlier languages had procedures and functions. Procedures returned nothing (they just did something). Functions returned something. I guess someone decided it was unnecessary to have both since a function could simply be void (as used in C). I just wrote a quick function to store data in the database. Since the data was filtered in several levels the odds of an error was negligible, nonetheless, I included in the function an alert, that would echo on an error, so returning even an error alert wasn't necessary. (This is an in-house site, that wouldn't be for public use) so having the function return anything was completely unnecessary.

一些早期的语言有程序和功能。程序什么也没有返回(它们只是做了一些事情)。函数返回。我猜有人认为没有必要同时使用这两个函数,因为一个函数可以是空的(如C中使用的)。由于数据是在几个级别进行过滤的,所以出现错误的几率是可以忽略不计的,不过,我在函数中加入了一个警告,它会对错误进行响应,因此即使返回一个错误警报也是不必要的。(这是一个内部站点,不会用于公共用途)所以让函数返回任何东西是完全不必要的。

Since the question was why we should ALWAYs return a value, it's not about why it's sometimes good to return a value, but what reason exists to demand we should always return a value, and there is no valid reason to ALWAYs return a value from a function.

既然问题是为什么我们总是要返回一个值,这不是为什么返回一个值有时是好的,而是有什么原因需要我们总是返回一个值,并且没有任何正当的理由总是返回一个函数的值。