可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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!
回答1:
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.
回答2:
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.
回答3:
I wouldn't consider it bad practice at all. It's widely used.
回答4:
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.
回答5:
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