JAVA编程:Good Java Style: Part 1
还得说上一点,就java本质而言,是面相对象的,但是你有没有发现,java也不全是,比如说基本类型,int,那他就是整型而不是对象,转换类型是还得借助包装类。GoodJavaStyle:Part1ByThorntonRose
Introduction
Havingworkedasasoftwaredeveloperandconsultantformanyyears,Ihaveseenalargeamountofcodeinavarietyofprogramminglanguages.Ithasrunthegamutfromeleganttougly,andunfortunatelymuchofithasbeenugly.Ihopetopersuadeyou,andmyfellowdevelopers,thatweshouldgiveasmuchattentiontothestyleofourcodeaswegivetotheuserinterfaceandothervisiblepartsofanapplication.Inthisthefirstpartofatwopartseries,IexplainwhyweshouldcareabouthowourcodelooksandillustratesomegeneralelementsofgoodJavastyle.
WhyStyleMatters
EventhoughJavaisusedtowriteprogramsratherthanprose,itisstillusedtoexpressthoughtsandideas.And,inadditiontoconveyinginformation,thosethoughtsandideasmustactuallydosomething.Worryingaboutgoodstylemayseemlikeawasteoftime,butitbehoovesustowriteourcodesuchthatthethoughtsandideasitexpressesareexceptionallyclear.
Hereareseveralreasonsforusinggoodstyle:
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++快 接着就是EJB了,EJB就是Enterprise JavaBean, 看名字好象它是Javabean,可是它和Javabean还是有区别的。它是一个体系结构,你可以搭建更安全、更稳定的企业应用。它的大量代码已由中间件(也就是我们常听到的 Weblogic,Websphere这些J2EE服务器)完成了,所以我们要做的程序代码量很少,大部分工作都在设计和配置中间件上。 是一种语言,用以产生「小应用程序(Applet(s)) 任职于太阳微系统的詹姆斯·高斯林等人于1990年代初开发Java语言的雏形,最初被命名为Oak,目标设置在家用电器等小型系统的程序语言 是一种语言,用以产生「小应用程序(Applet(s)) Java语言支持Internet应用的开发,在基本的Java应用编程接口中有一个网络应用编程接口(java net),它提供了用于网络应用编程的类库,包括URL、URLConnection、Socket、ServerSocket等。Java的RMI(远程方法激活)机制也是开发分布式应用的重要手段。 当然你也可以参加一些开源项目,一方面可以提高自己,另一方面也是为中国软件事业做贡献嘛!开发者在互联网上用CVS合作开发,用QQ,MSN,E-mail讨论联系,天南海北的程序员分散在各地却同时开发同一个软件,是不是很有意思呢? 应用在电视机、电话、闹钟、烤面包机等家用电器的控制和通信。由于这些智能化家电的市场需求没有预期的高,Sun公司放弃了该项计划。随着1990年代互联网的发展 Java是一种计算机编程语言,拥有跨平台、面向对java 任职于太阳微系统的詹姆斯·高斯林等人于1990年代初开发Java语言的雏形,最初被命名为Oak,目标设置在家用电器等小型系统的程序语言 J2SE开发桌面应用软件比起 VC,VB,DEPHI这些传统开发语言来说,优势好象并不明显。J2ME对于初学者来说,好象又有点深奥,而且一般开发者很难有开发环境。 http://www.jdon.com/去下载,或到同济技术论坛的服务器ftp://nro.shtdu.edu.cn去下,安装上有什么问题,可以到论坛上去提问。 有时间再研究一下MVC结构(把Model-View-Control分离开的设计思想) 一般学编程语言都是从C语开始学的,我也不例外,但还是可能不学过程语言而直接学面向对象语言的,你是刚接触语言,还是从C开始学比较好,基础会很深点,如果你直接学习JAVA也能上手,一般大家在学语言的时候都记一些语言的关键词,常有的包和接口等。再去做逻辑代码的编写,以后的学习过程都是从逻辑代码编写中提升的,所以这方面都是经验积累的。你要开始学习就从 Pet Store.(宠物店)是SUN公司为了演示其J2EE编程规范而推出的开放源码的程序,应该很具有权威性,想学J2EE和EJB的朋友不要 错过了。 一般学编程语言都是从C语开始学的,我也不例外,但还是可能不学过程语言而直接学面向对象语言的,你是刚接触语言,还是从C开始学比较好,基础会很深点,如果你直接学习JAVA也能上手,一般大家在学语言的时候都记一些语言的关键词,常有的包和接口等。再去做逻辑代码的编写,以后的学习过程都是从逻辑代码编写中提升的,所以这方面都是经验积累的。你要开始学习就从 http://www.jdon.com/去下载,或到同济技术论坛的服务器ftp://nro.shtdu.edu.cn去下,安装上有什么问题,可以到论坛上去提问。 Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。 自从Sun推出Java以来,就力图使之无所不包,所以Java发展到现在,按应用来分主要分为三大块:J2SE,J2ME和J2EE,这也就是Sun ONE(Open Net Environment)体系。J2SE就是Java2的标准版,主要用于桌面应用软件的编程;J2ME主要应用于嵌入是系统开发,如手机和PDA的编程;J2EE是Java2的企业版,主要用于分布式的网络程序的开发,如电子商务网站和ERP系统。 你现在最缺的是实际的工作经验,而不是书本上那些凭空想出来的程序。
页:
[1]