|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
还得说上一点,就java本质而言,是面相对象的,但是你有没有发现,java也不全是,比如说基本类型,int,那他就是整型而不是对象,转换类型是还得借助包装类。GoodJavaStyle:Part1
ByThorntonRose
Introduction
Havingworkedasasoftwaredeveloperandconsultantformanyyears,Ihaveseenalargeamountofcodeinavarietyofprogramminglanguages.Ithasrunthegamutfromeleganttougly,andunfortunatelymuchofithasbeenugly.Ihopetopersuadeyou,andmyfellowdevelopers,thatweshouldgiveasmuchattentiontothestyleofourcodeaswegivetotheuserinterfaceandothervisiblepartsofanapplication.Inthisthefirstpartofatwopartseries,IexplainwhyweshouldcareabouthowourcodelooksandillustratesomegeneralelementsofgoodJavastyle.
WhyStyleMatters
EventhoughJavaisusedtowriteprogramsratherthanprose,itisstillusedtoexpressthoughtsandideas.And,inadditiontoconveyinginformation,thosethoughtsandideasmustactuallydosomething.Worryingaboutgoodstylemayseemlikeawasteoftime,butitbehoovesustowriteourcodesuchthatthethoughtsandideasitexpressesareexceptionallyclear.
Hereareseveralreasonsforusinggoodstyle[from"JavaCodeConventions,"SunMicrosystems]:
80%ofthelifetimecostofasoftwareproductgoestomaintenance.
Hardlyanysoftwareismaintainedforitswholelifebytheoriginalauthor(s).
Usinggoodstyleimprovesthemaintainabilityofsoftwarecode.
Ifthesourcecodeisshippedwiththesoftware,itshouldbeaswell-packaged,clean,andprofessionalastherestoftheproduct.
Writingcodewithgoodstylealsoprovidesthefollowingbenefits:
Itimprovesthereadability,consistency,andhomogeneityofthecode,whichmakesiteasiertounderstandandmaintain.
Itmakesthecodeeasiertotraceanddebug,becauseitsclearandconsistent.
Itallowsyoutocontinuemoreeasilywhereyouoranotherprogrammerstopped,particularlyafteralongperiodoftime.
Itincreasesthebenefitofcodewalkthroughs,becausetheparticipantscanfocusmoreonwhatthecodeisdoing.
GeneralGuidelines
WritingJavawithgoodstyleisnothard,butitdoesrequireattentiontodetail.Herearesomegeneralguidelinestofollow:
Makethecodeclearandeasytoread.
Makethecodeconsistent.
Useobviousidentifiernames.
Logicallyorganizeyourfilesandclasses.
Haveonlyoneclassperfile(notincludinginnerclasses).
Useamaximumlinewidthof80-90characters.
Usewhitespaceand/orotherseparatorsjudiciously.
Usespacesinsteadoftabsforindentation.
Tabsvs.Spaces
Tabsvs.spacesisoneofseveralreligiousissuesrelatedtowritingcode,andIamnotsuggestingthatthereisonlyonerightway.Iespouseusingspacesbecauseitensuresthatmycodewilllookthesameinmyeditorasitdoesinyoureditorandviceversa.Ifyoufeelthatusingspacesinsteadoftabs"justaintright",thenbyallmeansusetabs.
BracesandIndentation
Indentstyle(cf.,Raymond,"IndentStyle"),ortheplacementofbraces("{"and"}")andtheassociatedindentationofcode,isanotherofthereligiousissuesrelatedtowritingcode.ThereareseveralindentstylescommontoC-stylelanguageslikeJava,andIamnotgoingtosuggestthatoneofthemissuperior.Inmostoftheexamplecodeinthisarticle,IusewhatisusuallyreferredtoasK&Rstyle.IfyoudontlikeK&R,byallmeansuseanotherstyle.
Comments
TherearetwotypeofcommentsthatyoucanputinyourJavacode:Javadoccomments(alsocalleddocumentationcomments)andimplementationcomments.JavadoccommentscanbeextractedbythejavadoctooltoproduceAPIdocumentation.Implementationcommentsarethosecommentsthatexplainthehowandwhyofthecode.UsethefollowingguidelinesforcommentingyourJavacode:
UseJavadoccommentswherevertheyareallowed(onclassesandmethodsatminimum).
Useblockcommentsratherthanend-of-line/trailingcomments,exceptinspecialcases,suchasvariabledeclarations.
Also,keepinmindthatgoodcommentsarehelpful;badcommentsareanuisance.
Example1.BadCommentStyle
//applyRotAscii()--ApplyASCIIROT
privatevoidapplyRotAscii(){
try{
introtLength=Integer.parseInt(rotationLengthField.getText().trim());//getrotlen
RotAsciicipher=newRotAscii(rotLength);//newcipher
textArea.setText(cipher.transform(textArea.getText()));//transform
}catch(Exceptionex){
/*Showexception*/
ExceptionDialog.show(this,"Invalidrotationlength:",ex);}
}
Example2.GoodCommentStyle.
/**
*ApplytheASCIIrotationciphertotheuserstext.Thelengthisretrieved
*fromtherotationlengthfield,andtheuserstextisretrievedfromthe
*textarea.
*
*@authorThorntonRose
*/
privatevoidapplyRotAscii(){
introtLength=0;//rotationlength
RotAsciicipher=null;//ASCIIrotationcipher
try{
//Getrotationlengthfieldandconverttointeger.
rotLength=Integer.parseInt(rotationLengthField.getText().trim());
//CreateASCIIrotationcipherandtransformtheuserstextwithit.
cipher=newRotAscii(rotLength);
textArea.setText(cipher.transform(textArea.getText()));
}catch(Exceptionex){
//Reporttheexceptiontotheuser.
ExceptionDialog.show(this,"Invalidrotationlength:",ex);
}
}
BlocksandStatements
Usethefollowingguidelinesforwritingblocksandstatements:
Putonlyonestatementperline.
Alwaysusebraceswithcontrolstatements(e.g.,if).
Considermarkingtheendofablockwithacomment(e.g.,}//endif),particularlywithlongornestedblocks.
Putvariabledeclarationsatthebeginningofablock.
Alwaysinitializevariables.
Ifyouwanttobeaperfectionist,left-alignvariablenames.
Indentthecaseclausesinaswitchblock.
Putwhitespacebeforeandafteroperators.
Inif,for,orwhile,putwhitespacebeforethe"(".
Usewhitespaceandparenthesesinexpressionstoincreasereadability.
Variablesusedinforloopsaretheexceptiontoputtingvariablesatthebeginningofablock.Theloopvariable(s)maybedeclaredintheinitializationpartoftheforstatement,e.g.,for(inti=0;...)
.
Puttingacommentattheendofablockcanhelpyoutrackdownaccidentallydeletedclosingbraces.Findingthoseinalargesourcefilecansometimesdriveyounearlycrazy.
Example3.BadBlockStyle.
try{
for(inti=0;i<5;i++){
...
}
intthreshold=calculateThreshold();
floatvariance=(threshold*2.8)-1;
intc=0;
if(threshold<=15)c=calculateCoefficient();
switch(c){
case1:setCeiling(c*2);break;
case2:setCeiling(c*3);break;
else:freakOut();
}
}catch(Exceptionex){...}
Example4.GoodBlockStyle.
try{
intthreshold=0;
floatvariance=0.0;
intcoefficient=0;
//Prepare5cycles.
for(inti=0;i<5;i++){
prepareCycle(i);
}
//Calculatethethresholdandvariance.
threshold=calculateThreshold();
variance=(threshold*2.8)-1;
//Ifthethresholdislessthanthemaximum,calculatethecoefficient.
//Otherwise,throwanexception.
if(threshold<=MAX_THRESHOLD){
coefficient=calculateCoefficient();
}else{
thrownewRuntimeException("Thresholdexceeded!");
}
//Settheceilingbasedonthecoefficient.
switch(coefficient){
case1:
setCeiling(coefficient*2);
break;
case2:
setCeiling(coefficient*3);
break;
else:
freakOut();
}//endswitch
}catch(Exceptionex){
...
}//endtry
RelatedLinks
Tabsvs.Spaces,JamieZawinski.
WritingRobustJavaCode―TheAmbysoftInc.CodingStandardsforJava,ScottAmbler.
DraftJavaCodingStandard,DougLea.
JavaCodeConventions,SunMicrosystems,Inc.
HowtoWriteDocCommentsforJavadoc,SunMicrosystems,Inc.
TheJargonFile(knowninprintasTheNewHackersDictionary),EricS.Raymond.
IndentStyle,TheJargonFile,EricS.Raymond.
References
JavaCodeConventions.Copyright)1995-2000SunMicrosystems,Inc.
AbouttheAuthor
ThorntonRoseisacontractsoftwaredeveloperinAtlanta,Ga.Hecanbereachedviae-mailatthornton.rose@mindspring.com.
主要缺点就是:速度比较慢,没有C和C++快 |
|