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

后端 未结 12 983
孤独总比滥情好
孤独总比滥情好 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:38

    It sometimes depends on the language and what kinds of "resources" that you are using (e.g. open file handles).

    In C, Style 2 is definitely safer and more convenient because a function has to close and/or release any resources that it obtained during execution. This includes allocated memory blocks, file handles, handles to operating system resources such as threads or drawing contexts, locks on mutexes, and any number of other things. Delaying the return until the very end or otherwise restricting the number of exits from a function allows the programmer to more easily ensure that s/he properly cleans up, helping to prevent memory leaks, handle leaks, deadlock, and other problems.

    In C++ using RAII-style programming, both styles are equally safe, so you can pick one that is more convenient. Personally I use Style 1 with RAII-style C++. C++ without RAII is like C, so, again, Style 2 is probably better in that case.

    In languages like Java with garbage collection, the runtime helps smooth over the differences between the two styles because it cleans up after itself. However, there can be subtle issues with these languages, too, if you don't explicitly "close" some types of objects. For example, if you construct a new java.io.FileOutputStream and do not close it before returning, then the associated operating system handle will remain open until the runtime garbage collects the FileOutputStream instance that has fallen out of scope. This could mean that another process or thread that needs to open the file for writing may be unable to until the FileOutputStream instance is collected.

提交回复
热议问题