Android Code Convention

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

1AndroidCodeConventionsJuly1,2011.2WhyCodeConventions•80%ofthelifetimecostofapieceofsoftwaregoestomaintenance.•Hardlyanysoftwareismaintainedforitswholelifebytheoriginalauthor.•Codeconventionsimprovethereadabilityofthesoftware,allowingengineerstounderstandnewcodemorequicklyandthoroughly.•Ifyoushipyoursourcecodeasaproduct,youneedtomakesureitisaswellpackagedandcleanasanyotherproductyoucreate.3PrincipalTherulesbelowarenotguidelinesorrecommendations,butstrictrules.Changeswillnotbeacceptediftheydonotadheretotheserules.Notallexistingcodefollowstheserules,butallnewcodeisexpectedto.4Indentation•Usefourspacesastheunitofindentation.•DON’Tusetabs•Avoidlineslongerthan100characters1.Exception:ifacommentlinecontainsanexamplecommandoraliteralURLlongerthan100characters,thatlinemaybelongerthan100charactersforeaseofcutandpaste.2.Exception:importlinescangooverthelimitbecausehumansrarelyseethem.Thisalsosimplifiestoolwriting.5Declarations•Onedeclarationperline•Trytoinitializelocalvariableswherethey’redeclared.intlevel,size;intlevel;//indentationlevelintsize;//sizeoftable6Don'tIgnoreExceptions•Throwtheexceptionuptothecallerofyourmethod•Throwanewexceptionthat'sappropriatetoyourlevelofabstraction•Handletheerrorgracefullyandsubstituteanappropriatevalueinthecatch{}block.•CatchtheExceptionandthrowanewRuntimeException.Thisisdangerous:onlydoitifyouarepositivethatifthiserroroccurs,theappropriatethingtodoiscrash.•Lastresort:ifyouareconfidentthatactuallyignoringtheexceptionisappropriatethenyoumayignoreit,butyoumustalsocommentwhywithagoodreasonvoidsetServerPort(Stringvalue){try{serverPort=Integer.parseInt(value);}catch(NumberFormatExceptione){}}7Don'tCatchGenericException•Catcheachexceptionseparatelyasseparatecatchblocksafterasingletry.ThiscanbeawkwardbutisstillpreferabletocatchingallExceptions.Bewarerepeatingtoomuchcodeinthecatchblocks.•Refactoryourcodetohavemorefine-grainederrorhandling,withmultipletryblocks.SplituptheIOfromtheparsing,handleerrorsseparatelyineachcase.•Rethrowtheexception.Manytimesyoudon'tneedtocatchtheexceptionatthislevelanyway,justletthemethodthrowit.Remember:exceptionsareyourfriend!Whenthecompilercomplainsyou'renotcatchinganexception,don'tscowl.Smile:thecompilerjustmadeiteasierforyoutocatchruntimeproblemsinyourcode.8Don'tUseFinalizersPros:•Canbehandyfordoingcleanup,particularlyofexternalresources.Cons:•Therearenoguaranteesastowhenafinalizerwillbecalled,oreventhatitwillbecalledatall.Decision:wedon'tusefinalizers.9FullyQualifyImportsimportfoo.*;importfoo.Bar;Pros:Potentiallyreducesthenumberofimportstatements.Pros:Makesitobviouswhatclassesareactuallyused.Makescodemorereadableformaintainers.10WriteShortMethods•Totheextentthatitisfeasible,methodsshouldbekeptsmallandfocused.•Longmethodsaresometimesappropriate•Ifamethodexceeds40linesorso,thinkaboutwhetheritcanbebrokenupwithoutharmingthestructureoftheprogram.11LimitVariableScope•Thescopeoflocalvariablesshouldbekepttoaminimum•Localvariablesshouldbedeclaredatthepointtheyarefirstused•Oneexceptiontothisruleconcernstry-catchstatements.•Loopvariablesshouldbedeclaredintheforstatementitselfunlessthereisacompellingreasontodootherwise12UseStandardBraceStyleif(condition){body();}if(condition)body();if(condition)body();13FollowFieldNamingConventionsNon-public,non-staticfieldnamesstartwithm.Staticfieldnamesstartwiths.Otherfieldsstartwithalowercaseletter.Publicstaticfinalfields(constants)areALL_CAPS_WITH_UNDERSCORES.publicclassMyClass{publicstaticfinalintSOME_CONSTANT=42;publicintpublicField;privatestaticMyClasssSingleton;intmPackagePrivate;privateintmPrivate;protectedintmProtected;}publicclassMyClass{publicstaticfinalintSOME_CONSTANT=42;publicintpublicField;privatestaticMyClasssSingleton;intmPackagePrivate;privateintmPrivate;protectedintmProtected;}14TreatAcronymsasWordsGoodBadXmlHttpRequestXMLHTTPRequestgetCustomerIdgetCustomerIDclassHtmlclassHTMLStringurlStringURLlongidlongID15

1 / 15
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功