JAVA编程风格简析Word格式文档下载.docx
《JAVA编程风格简析Word格式文档下载.docx》由会员分享,可在线阅读,更多相关《JAVA编程风格简析Word格式文档下载.docx(13页珍藏版)》请在冰点文库上搜索。
privateintage;
privateColorcolor;
/*Theconstructorshouldbeplacedinthebeginning*/
publicCar(intage,Colorcolor){
this.age=age;
this.color=color;
}
/*Examplemethod*/
publicintgetAge(){
returnage;
/*Themainmethodisoptional,butlookslikethis.
Ifitexists,itiseitherthefirstorthelast
methodintheclass*/
publicstaticvoidmain(String[]args){
...
注意类名和大括号间的空格!
方法
方法一般定义为public。
当然,如果方法仅仅在当前类用到可以定义为private,而如果希望一个子类沿用这个方法则不同,这时候的方法应定义为protected。
java中的方法定义很有趣,它们一般小写字母开头,如果有两个字组成,第二个字的首字母则大写。
因此名字的描述性是至关重要的。
这使你不用阅读整篇代码来判断这是一个什么方法。
在给自己的方法取名时应尽量不要太短或者太长,另一个需要注意的是大多方法使用动词(动宾短语)。
例如:
publicvoideat(){}
publicvoideatBananas(){}
Selector(选择器)方法有get前缀,后缀是它们将要get的,比如
publicintgetBananas(){}
Mutator(存取器)方法则有set前缀,后缀则是他们要set的,比如
publicvoidsetBananas(intamount){}
注意mutators大多无返回值。
方法的参数应当以如下方式给出:
publicvoidaMethod(typeparameter1,typeparameter2,...,typeparametern){}
如果参数过长,也可以断开为几行,应对齐向下排列如:
publicvoidaMethod(typeparameter1,typeparameter2,...,
typeparametern,typeparametern+1,...,
typeparameterm,typeparameterm+1){}
另外要注意类的左束括号应在方法的右束括号之后而非下一行:
publicintaMethod(){
inti=0;
if(i==0)
System.out.println("
success!
"
);
为了文件可读性好,还要注意语句最好写在同一行,当然一行写不下是可以断行的,比如行字母超过80。
fields
比如变量,如果不希望它永久有效,应设为private。
如果一个变量在类中不发生任何动作(比如数据结构中的node)则可以设置为public,常量一般声明为public。
如果不能确定一个变量到底该声明为什么,应暂且声明为private。
field的名字一般使用小写字母,不要使用下横线或其他特殊字符。
如果变量包含两个字,那么第二个字的首字母大写。
比如:
inti,j,k;
Datedate;
doublemyField;
常量一般全部大写,也可以包含下横线:
publicstaticfinalintMAX_SIZE_OF_DATABASE
fields的名字通常为名词。
较重要的fields更应具备描述性,比如程序中包含一个游戏的得分,那可以用score来代表。
如果变量变化较频繁,那使用一个单一字符来代表就ok了:
i,j,k通常代表整数
r,t,u,v,w通常代表实数
x,y,z通常是并列出现或代表浮点数
s,s1,s2,通常代表字符串
c,ch通常代表字符
f,file通常代表文件
tmp,temp通常代表临时变量
ctr,cnt,cntr一般代表计数器(如果i,j,k这些变量已被使用)
dummy,foo,bar一般代表哑元变量
args是main-method的主参数名
缩排与换行
每行长度不得超过80字符。
如果需要可以折行时,也应当与上一行有共同的缩排距离。
代码应如何交错、如何建立新行、在哪里建立允许、哪里不允许都有一些一般约定,缩排空格一般为2个或4个空格。
条件表达式
如果见到如下语法表达式:
if(expr)
statement1;
else
statement2;
代码行向右错排两个空格如上所示。
如果在一个表达式中有超过一条的声明,则需要大括号:
if(expr){
}else{
statement3;
statement4;
有时我们会希望在表达式中使用表达式(比如条件嵌套),这时应注意else表达式,它的位置很容易出错!
如例:
if(expr1){
}elseif(expr2)
elseif(expr3){
statement5;
}else{
statement6;
statement7;
注意大括号位置!
Loops
while-loop语法如下:
while(expr){
for-loop语法如下:
for(expr1;
expr2;
expr3){
仅一条声明时大括号省略:
while(expr)
statement;
expr3)
例如,我们写一个procedure写出1到10这十个数字:
for(i=1;
i<
=10;
i++)
System.out.println(i);
try-catch语法形如:
try{
statements;
}catch(ExceptionClasse){
如果try-catch语句后跟随finally子句则形如:
}finally{
新行
每一行最好只阐述一件事情。
比如,一行包含一个声明、一个条件语句、一个循环等。
不论多小,最好不要一行办两件事及以上。
例如不要把一个if表达式或循环语句的主体放置在同一行,这样的表达式断行的易读性会更高。
通常,互相协作的代码应放在一起,为保证代码美观可读,我们应将代码的不同代码段放置在不同的段落。
不过要牢记断行不要太过分!
比如:
publicintfactorial(intn){
intresult=1;
for(inti=1;
=n;
result*=i;
returnresult;
给自己的代码加入注释
注释就是类的描绘、方法存在的原因、它完成了什么以及它对它其中(变量)的作用域。
假定阅读你代码的人已经知道这是什么语言,所以不需要注释语句功能,尽量使用简短而有描述力的注释。
Java有两种类型的注释:
//Thisisacommentthatcontinuesuntiltheendoftheline.
/*Thisisacomment.Itgoesonandonandonandonandonandonandon
andonandonandonandonandonandonandonandonandonandonand
onandonandonandonandonandonandonandonandendslikethis:
*/
/**
*ThisisaJavaDoccomment.MoreaboutJavaDocinthenextsection.
*/
如果在注释中加入注释则会出错:
/*Youarenotallowedtodoanythinglikethis/*becausethecompilerwill
complain,ifyouarelucky*/DON'
TDOTHIS!
Anddon'
twritecommentsin
uppercaseeither...*/
注释应放在它要解释内容上下,这样会让代码更易于理解。
不要注释一些语言的语句功能:
i++;
//Add1toi
更不要让自己的代码处于这种状态:
/*don'
tplacecommentswhere
theydon'
tbelong*/
较短的注释既可被放在被注释代码上下,而长注释则习惯性的放在代码之上:
/*Commentscanbeplacedbeforethe
blockthatistobecommented*/
或者:
i++){
//shortcommentscanbeplacedlikethis
tmp++;
//ifnecessary,theycontinuehere
不要写没用的注释:
//changethislater
Excuseme,这句肯定是胡扯!
不要写自己都看不懂的注释:
//BMW
BMW?
如果你能连续十天记住这是什么意思的话,那么你的记忆真是不错了。
所以不要写没人能看懂的注释,ok?
最后重申一下:
写简短而富于描述性的注释,把它们放在该放的地方,而不要考验你自己的记忆力!
JavaDoc-文档工具
JavaDoc不仅是另一种给代码加注释的仿佛咱,更是一个文档工具。
类、方法和一些重要地方需要用JavaDoc来注释。
这并不是说你可以放弃常规的注释,这两者在代码中应该是相辅相成、互相弥补的关系。
类被注释如:
*Carrepresentscars...Adescriptionoftheclass
*shouldbeplacehere.Notethatthedescriptionbegins
*onthesecondlineandthatthereisaspacebetween
*theasterixandthetext.Nextwewilladdsomefields
*indicatingwhotheauthorsoftheclassareand
*otherusefulinformation.Noticethenewline!
*
*@authorJerryMeng
*@version%I%,%G%
注意JavaDoc结束和类开始间无空行。
方法被注释如:
*Adescriptionofwhatthemethoddoes...
*@paramnadescriptionoftheparameter
*@returnadescriptionofthereturnvalue
某些不是全部,被JavaDoc注释区域如:
*Shortdescriptionofthevariable(oneline)
typevariable;
什么应当使用JavaDoc做注释?
如何注释的恰当呢?
可以这样想,JavaDoc中所作的注释都可以在类的文档中看到。
所有读这个类的文档的读者都会明白这个类所完成的功能、它包括的方法、如何使用这些方法及方法的返回值。
一些作用域,比如public的变量或常量将会一目了然。
任何不了解这个类内部结构的人都可以轻松的调用它。
这便是你用JavaDoc可以轻松提供的信息。
而使用一般注释的地方,一般是给那些可能修改你的类代码的程序员,它们一般描述了类的内部信息和结构。
下面我写一下car的类来描述一个编程风格好的java类应该是怎样的。
当然这仅仅是一个小例子(apartfromselectorandmutatormethods),仅仅是在考虑JAVA编程风格上一个参考而已。
importjava.awt.Color;
*Thisisaclassrepresentingcars.Acarhascertainfeatures,such
*ascolor,age,numberofdoorsetcandacarcanberepainted,
*thetankcanbefilledetc.
*Themaximumsizeofthetankinlitres.
privatestaticfinaldoubleTANK_SIZE=100.0;
*Thecolorofthecar.
*Theageofthecar.
*Thenumberofdoorsofthecar.
privateintdoors;
*Theamountofgasolineinthetank.
privatedoublegasoline;
*Classconstructor,whichconstructsabrandnew,blackcarwith
*fivedoorsandafulltank.
publicCar(){
this(Color.black,0,5,TANK_SIZE);
*Classconstructorspecifyingthecolor,age,numberofdoors
*andlitresofgasoline
*@paramcolorThecolorofthecar
*@paramageTheageofthecar
*@paramdoorsThenumberofdoors
*@paramkmKilometresdriven
*@paramgasolineThelitresofgasoline
publicCar(Colorcolor,intage,intdoors,doublegasoline){
this.doors=doors;
this.gasoline=gasoline;
*Returnsthecolorofthecar
publicColorgetColor(){
returncolor;
*Repaintsthecar(i.e.changesitscolor)
publicvoidsetColor(Colorcolor){
*Returnstheageofthecar
*Returnsthenumberofdoorsofthecar
publicintgetDoors(){
returndoors;
*Returnstheamountofgasolineinthetank
publicdoublegetGasoline(){
returngasoline;
*Fillsthetank.Theamountofgasolinecannotexceed
*thesizeofthetank.Inthatcase,thetankwillbe
*filledtothemaximumandtherestwillrunoutin
*thesand.
*@paramgasTheamountofgasolinetoputinthetank
publicvoidsetGasoline(doublegas){
if(gasoline+gas<
=TANK_SIZE)
gasoline+=gas;
gasoline=TANK_SIZE;