Any research on maintainability of “guard statement” vs. “single function exit point” paradigm available?

前端 未结 1 397
挽巷
挽巷 2020-12-30 08:30

I\'m wondering if there has been any research (both casual and robust) on the maintainability of projects that use the \"guard statement\" paradigm vs. the \"single functio

相关标签:
1条回答
  • 2020-12-30 08:45

    Forcing to have single exit points have some problems of their own.

    The first one is that it may lead to complex constructions. Image a function in which you have to open a file, read a line, convert the line to a number and return that number or zero if something goes wrong. With a single exit point, you end up using lots of nested if's (if file exists open it, if open succeeds read the line, if read succeeds convert the value to an integer), which makes your code unreadable. Some of it can be solved by having a label at the end of the function and using goto's (we had to use that in the past since we also used the single exit point and preferred readability) but it's not ideal.

    Second, if you are using exceptions you are forced to catch everything if you want your single exit point again.

    So, personally, I prefer putting lots of checks (and asserts) in the beginning and during the execution of the function, and exit the function at the first sign of trouble.

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