How to exit an if clause

前端 未结 13 1744
故里飘歌
故里飘歌 2020-12-04 08:45

What sorts of methods exist for prematurely exiting an if clause?

There are times when I\'m writing code and want to put a break statement

13条回答
  •  醉梦人生
    2020-12-04 09:11

    Generally speaking, don't. If you are nesting "ifs" and breaking from them, you are doing it wrong.

    However, if you must:

    if condition_a:
       def condition_a_fun():
           do_stuff()
           if we_wanna_escape:
               return
       condition_a_fun()
    if condition_b:
       def condition_b_fun():
           do_more_stuff()
           if we_wanna_get_out_again:
               return
       condition_b_fun()
    

    Note, the functions don't HAVE to be declared in the if statement, they can be declared in advance ;) This would be a better choice, since it will avoid needing to refactor out an ugly if/then later on.

提交回复
热议问题