Programming style: should you return early if a guard condition is not satisfied?

后端 未结 12 938
孤独总比滥情好
孤独总比滥情好 2020-12-28 13:46

One thing I\'ve sometimes wondered is which is the better style out of the two shown below (if any)? Is it better to return immediately if a guard condition hasn\'t been sat

12条回答
  •  醉梦人生
    2020-12-28 14:20

    Number 1 is typically the easy, lazy and sloppy way. Number 2 expresses the logic cleanly. What others have pointed out is that yes it can become cumbersome. This tendency though has an important benefit. Style #1 can hide that your function is probably doing too much. It doesn't visually demonstrate the complexity of what's going on very well. I.e. it prevents the code from saying to you "hey this is getting a bit too complex for this one function". It also makes it a bit easier for other developers that don't know your code to miss those returns sprinkled here and there, at first glance anyway.

    So let the code speak. When you see long conditions appearing or nested if statements it is saying that maybe it would be better to break this stuff up into multiple functions or that it needs to be rewritten more elegantly.

提交回复
热议问题