2014年12月2日 星期二

[Experience] 程式語言裡的goto真有這麼可怕!?

這幾天看到網路上又有人在吵goto的問題,這讓我想起之前工作同事間的爭執,A同事在他改的程式碼裡使用goto做錯誤處理, B同事看到A改的程式碼就要求A把goto的程式碼全改掉,理由是別人都說不要用所以不該這樣寫, 但是B卻說不出不該用的原因所以兩人就發生了激辯,其實goto也沒那麼恐怖而且也不是不能用。

以下節錄EFI1.10 Driver Writer's Guide的內容 (3.11.7):
In general, the goto construct is not used. However, it is acceptable to use goto for error handling and thus exiting a routine in an error case. A goto allows the error exit code to be contained in one place at the end of a routine. This location reduces software life cycle maintenance issues, as there can be one copy of error cleanup code per routine. If a goto is not used for this case, then the error cleanup code tends to get replicated multiple times, which tends to induce errors in code maintenance.

另外不該使用goto的原因和正確的使用時機clean code這本書也說得很清楚:
 Some programmers follow Edsger Dijkstra’s rules of structured programming. Dijkstra said that every function, and every block within a function, should have one entry and one exit. Following these rules means that there should only be one return statement in a function, no break or continue statements in a loop, and never, ever, any goto statements. While we are sympathetic to the goals and disciplines of structured programming, those rules serve little benefit when functions are very small. It is only in larger functions that such rules provide significant benefit. So if you keep your functions small, then the occasional multiple return, break, or continue statement does no harm and can sometimes even be more expressive than the single- entry, single-exit rule. On the other hand, goto only makes sense in large functions, so it should be avoided.

沒有留言:

張貼留言