仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1284|回复: 19
打印 上一主题 下一主题

[学习教程] JAVA编程:Good Java Style: Part 1

[复制链接]
活着的死人 该用户已被删除
跳转到指定楼层
#
发表于 2015-1-18 11:55:45 | 只看该作者 回帖奖励 |正序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

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++快
兰色精灵 该用户已被删除
19#
发表于 2015-5-6 19:41:27 | 只看该作者
你现在最缺的是实际的工作经验,而不是书本上那些凭空想出来的程序。
小魔女 该用户已被删除
18#
发表于 2015-4-30 09:38:44 | 只看该作者
自从Sun推出Java以来,就力图使之无所不包,所以Java发展到现在,按应用来分主要分为三大块:J2SE,J2ME和J2EE,这也就是Sun ONE(Open Net Environment)体系。J2SE就是Java2的标准版,主要用于桌面应用软件的编程;J2ME主要应用于嵌入是系统开发,如手机和PDA的编程;J2EE是Java2的企业版,主要用于分布式的网络程序的开发,如电子商务网站和ERP系统。
愤怒的大鸟 该用户已被删除
17#
发表于 2015-4-27 13:44:16 | 只看该作者
Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。
若相依 该用户已被删除
16#
发表于 2015-4-16 23:13:06 | 只看该作者
[url]http://www.jdon.com/[/url]去下载,或到同济技术论坛的服务器[url]ftp://nro.shtdu.edu.cn[/url]去下,安装上有什么问题,可以到论坛上去提问。
海妖 该用户已被删除
15#
发表于 2015-4-16 15:47:56 | 只看该作者
一般学编程语言都是从C语开始学的,我也不例外,但还是可能不学过程语言而直接学面向对象语言的,你是刚接触语言,还是从C开始学比较好,基础会很深点,如果你直接学习JAVA也能上手,一般大家在学语言的时候都记一些语言的关键词,常有的包和接口等。再去做逻辑代码的编写,以后的学习过程都是从逻辑代码编写中提升的,所以这方面都是经验积累的。你要开始学习就从
再现理想 该用户已被删除
14#
发表于 2015-4-11 02:11:14 | 只看该作者
Pet Store.(宠物店)是SUN公司为了演示其J2EE编程规范而推出的开放源码的程序,应该很具有权威性,想学J2EE和EJB的朋友不要 错过了。
飘灵儿 该用户已被删除
13#
发表于 2015-4-2 18:40:58 | 只看该作者
一般学编程语言都是从C语开始学的,我也不例外,但还是可能不学过程语言而直接学面向对象语言的,你是刚接触语言,还是从C开始学比较好,基础会很深点,如果你直接学习JAVA也能上手,一般大家在学语言的时候都记一些语言的关键词,常有的包和接口等。再去做逻辑代码的编写,以后的学习过程都是从逻辑代码编写中提升的,所以这方面都是经验积累的。你要开始学习就从
因胸联盟 该用户已被删除
12#
发表于 2015-3-27 00:11:05 | 只看该作者
有时间再研究一下MVC结构(把Model-View-Control分离开的设计思想)
飘飘悠悠 该用户已被删除
11#
发表于 2015-3-26 18:48:53 | 只看该作者
[url]http://www.jdon.com/[/url]去下载,或到同济技术论坛的服务器[url]ftp://nro.shtdu.edu.cn[/url]去下,安装上有什么问题,可以到论坛上去提问。
再见西城 该用户已被删除
10#
发表于 2015-3-22 19:42:31 | 只看该作者
J2SE开发桌面应用软件比起 VC,VB,DEPHI这些传统开发语言来说,优势好象并不明显。J2ME对于初学者来说,好象又有点深奥,而且一般开发者很难有开发环境。
活着的死人 该用户已被删除
9#
 楼主| 发表于 2015-3-20 01:40:51 | 只看该作者
任职于太阳微系统的詹姆斯·高斯林等人于1990年代初开发Java语言的雏形,最初被命名为Oak,目标设置在家用电器等小型系统的程序语言
谁可相欹 该用户已被删除
8#
发表于 2015-3-12 18:51:08 | 只看该作者
Java是一种计算机编程语言,拥有跨平台、面向对java
变相怪杰 该用户已被删除
7#
发表于 2015-3-6 02:38:41 | 只看该作者
应用在电视机、电话、闹钟、烤面包机等家用电器的控制和通信。由于这些智能化家电的市场需求没有预期的高,Sun公司放弃了该项计划。随着1990年代互联网的发展
不帅 该用户已被删除
6#
发表于 2015-2-18 09:13:43 | 只看该作者
当然你也可以参加一些开源项目,一方面可以提高自己,另一方面也是为中国软件事业做贡献嘛!开发者在互联网上用CVS合作开发,用QQ,MSN,E-mail讨论联系,天南海北的程序员分散在各地却同时开发同一个软件,是不是很有意思呢?
老尸 该用户已被删除
5#
发表于 2015-2-10 04:04:13 | 只看该作者
Java语言支持Internet应用的开发,在基本的Java应用编程接口中有一个网络应用编程接口(java net),它提供了用于网络应用编程的类库,包括URL、URLConnection、Socket、ServerSocket等。Java的RMI(远程方法激活)机制也是开发分布式应用的重要手段。
只想知道 该用户已被删除
地板
发表于 2015-2-9 04:24:58 | 只看该作者
是一种语言,用以产生「小应用程序(Applet(s))
板凳
发表于 2015-2-3 19:29:26 | 只看该作者
任职于太阳微系统的詹姆斯·高斯林等人于1990年代初开发Java语言的雏形,最初被命名为Oak,目标设置在家用电器等小型系统的程序语言
admin 该用户已被删除
沙发
发表于 2015-1-27 13:59:47 | 只看该作者
是一种语言,用以产生「小应用程序(Applet(s))
分手快乐 该用户已被删除
楼主
发表于 2015-1-26 06:47:39 | 只看该作者
接着就是EJB了,EJB就是Enterprise JavaBean, 看名字好象它是Javabean,可是它和Javabean还是有区别的。它是一个体系结构,你可以搭建更安全、更稳定的企业应用。它的大量代码已由中间件(也就是我们常听到的 Weblogic,Websphere这些J2EE服务器)完成了,所以我们要做的程序代码量很少,大部分工作都在设计和配置中间件上。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-9-29 12:21

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表