java中我們很常見(jiàn)的設(shè)計(jì)API的例子是對(duì)一個(gè)對(duì)象進(jìn)行增,刪,查,改.比如ObjectaddObject(Objectobj);ObjectdelObject(Objectobj);ObjectmodifyObject(Objectobj);成功返回obj,不成功(參數(shù)不合法,或已經(jīng)存在,或不存在)拋出異常還是intaddObject(Objectobj);intdelObject(Objectobj);intmodifyObject(Objectobj);如果成功返回0,不成功,返回其他數(shù)字還是booleanaddObject(Objectobj);booleandelObject(Objectobj);booleanmodifyObject(Objectobj);如果成功返回0,不成功(參數(shù)不合法,或已經(jīng)存在,或不存在),拋出異常感謝各位熱心回答,我已經(jīng)決定采用第一種方式了.原因:1.性能不是那么的關(guān)鍵;2絕大多數(shù)我們認(rèn)為參數(shù)是正確的.排除異常較返回Errorcode讓代碼更加簡(jiǎn)潔.補(bǔ)充:以下是從這里找到的一個(gè)回答,基本決定采用第一中方式,這或許是java語(yǔ)言本身的特點(diǎn),如果是c或cpp我更傾向于第二種方式.Exceptionsimposequiteanoverheadontheruntimeperformance,butmakesreasoningabouttheprogramflowdrasticallyeasier.Thisreducesfaultyprogramming(semanticerrors),especiallyasitforcesyoutodealwiththem-they'failsecurely'byterminatingtheprogramiftheyareignored.Theyareidealfor'situationswhicharenotsupposedtohappen'.Alsotheycantransportmetadatalikeastacktrace.Errorcodes,ontheotherhand,arelight-weight,fast,butforcesthemethodcallertoexplicitelycheckthem.Failuretodosooftenresultsinprogramflaws,whichcanrangefromsilentdatacorruption,securityholes,tonicefireworksifyourprogramhappenstoberunninginsideaspacerocket.
java 中如何處理設(shè)計(jì)一個(gè)方法
慕田峪4524236
2019-03-30 11:31:22