用AI赚第一桶💰低成本搭建一套AI赚钱工具,源码可二开。 广告
[TOC] ## 概述 goto并非完全有害的,程序最终不存在goto,是正确处理的结果,而非避免goto的目标 ## 合适的使用场景 ### 错误处理和goto ``` sub PurgeFiles (ByRef ErrorState As Error_code) //code ... errorState = FIleStatus_Success fileIindex=0 While(fileIndex <numFileToPurge) fileIndex = fileIndex +1 if Not (FindFile(fileList(fileIndex),fileToPurge)) Then ErrorState = FileStatus_FileFindError GoTo End_PROC End If if Not OpenFile(fileToPurge) Then errorState = FileStatus_FileOpenError GoTo End_PROC End If if Not OverwriteFIle(fileToPurge) Then errorState = FileStatus_FileOvereriteError GoTo End_PROC End If End While END_PROC: DeletePurgeFIleList(fileList,numFIlesToPurge) End Sub ``` 消除goto方式一:使用 if (但不不合适) bad 示例 ``` sub PurgeFiles (ByRef ErrorState As Error_code) // code errorState = FIleStatus_Success fileIindex=0 While(fileIndex <numFileToPurge And errorState = FileStatus_Success) fileIndex = fileIndex +1 If (FindFile(fileList(fileIndex),fileToPurge)) Then If OpenFile(fileToPurge) Then If Not Erase (fileToPurge) Then errorState = FileStatus_FileEraseError Else errorState = FileStatus_FileOverwriteError Else errorState = FileStatus_FileFindError Else If E,但也算代替goto比较好的方法nd While DeletePurgeFIleList(fileList,numFIlesToPurge) End Sub ``` 消除goto方式二:使用 try-findally 的局限性(比上一方法好) 如果早期代码既使用了错误码,又使用了异常,那么负责异常处理的代码就要为每一种可能的错误设置一个错误码 ### goto 和在 else 子句中共享代码 ``` if (statusOK){ if(dataAvaiable){ importantVariable = x; goto MIN_LOOP; } }else{ importantVariable = GetValue(): // lots of code } ``` 消除方式一: 使用子程序 ``` if (statusOK){ if(dataAvaiable){ importantVariable = x; DolotsOfCode(importantVariable) } }else{ importantVariable = GetValue(): DolotsOfCode(importantVariable) } ``` 消除方式二: 重新组织条件 ``` if ( (statusOK & dataAvaiable) || statusOK){ if( (statusOK & dataAvaiable) ){ importantVariable = x; goto MIN_LOOP; }else{ importantVariable = GetValue(): } // lots of code } ```