1AndroidCodeConventionsJuly1,2011.2WhyCodeConventions•80%ofthelifetimecostofapieceofsoftwaregoestomaintenance.•Hardlyanysoftwareismaintainedforitswholelifebytheoriginalauthor.•Codeconventionsimprovethereadabilityofthesoftware,allowingengineerstounderstandnewcodemorequicklyandthoroughly.•Ifyoushipyoursourcecodeasaproduct,youneedtomakesureitisaswellpackagedandcleanasanyotherproductyoucreate.3PrincipalTherulesbelowarenotguidelinesorrecommendations,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'tUseFinalizersPros:•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();13FollowFieldNamingConventionsNon-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