开发者

It's considered a bad pratice use return to end a function?

开发者 https://www.devze.com 2023-03-04 04:51 出处:网络
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

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开发者_如何学C is considered a bad practice or something like that.

Thanks!


Nope. Not at all. It's often an important piece of control flow, in fact:

for x in someiterable:
    if somecondition:
        return somevalue
return None

This might come up if you were iterating over a sequence looking for something that satisfies a particular condition. If you find that something, you return it and prevent any further processing. If you never find it, you return a default value.


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.


I wouldn't consider it bad practice at all. It's widely used.


For further interesting reading look up "multiple vs single return" on Google. Much heat there. The alternative is generally to hold your return in state, and only return it once, at the end. Personally I'd rather dump out asap rather than risk some state being modified further down the line; smaller more focussed methods help stop that happening.

I'd say your practice here is fine.


I use it when i'm too lazy to declare a flag and test it. But the fact is: If you use break, return, and that kind of instructions in the middle of your code, you will sometimes have to refactor it when adding functionnalities.

So I consider it a bad practice, but very much used. Well it's just my opinion :p

0

精彩评论

暂无评论...
验证码 换一张
取 消