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

后端 未结 5 1155
忘了有多久
忘了有多久 2021-01-19 10:46

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
{
           


        
相关标签:
5条回答
  • 2021-01-19 11:17

    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 讨论(0)
  • 2021-01-19 11:19

    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.

    0 讨论(0)
  • 2021-01-19 11:22

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

    0 讨论(0)
  • 2021-01-19 11:23

    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.

    0 讨论(0)
  • 2021-01-19 11:40

    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.

    0 讨论(0)
提交回复
热议问题