这被认为是一个糟糕的实践使用返回结束一个函数?(It's considered a bad pratice use return to end a function?)

我是一名PHP和ActionScript开发人员,在一些函数中,我使用return来结束它。 例:

private function lolsome(a:String):void { if(a == "abs"){return void;} // function's code }

我可以将函数的代码放入else代码中,但我更喜欢这种方式,因为在我看来,这样更清晰。 我只想知道这是否被认为是不好的做法或类似的事情。

谢谢!

I'm a PHP and ActionScript developer, and in some of my functions I use return to end it. Example:

private function lolsome(a:String):void { if(a == "abs"){return void;} // function's code }

I could just place the function's code into its else, but I prefer this way because in my opinion, this is more legible. I just want to know if this is considered a bad practice or something like that.

Thanks!

最满意答案

如果你在长时间复杂的函数中有返回值,我只会认为这是不好的做法,因为在查看它时可能难以理解其他算法。 然而,首先需要大的长功能是不好的做法(它们通常应该分成多个小功能)。

总的来说,我会考虑在函数开始时验证参数和状态,然后回到良好的习惯,甚至不是好的。

但仍然要小心,不要在主逻辑中抛弃具有多种不同回报的函数。

I would only consider it bad practice if you have returns inside long complicated functions because it can be harder for someone else to understand the algorithm when looking at it. However, it is bad practice to have big long functions in the first place (they should generally be split up into multiple smaller functions).

Overall, I would consider validating parameters and state at the beginning of a function and just returning to be good practice, not even just ok.

But still be careful not to litter a function with several different returns within the main logic.

更多推荐