|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
但是一些大型开发或者是保密型比较高的项目都会用java,原因有2点,一:java是开源的,不怕别人留后门,偷我工具,.net就不一样了,保持微软的一向风格,源代码不公开GoodJavaStyle:Part2
ByThorntonRose
Introduction
Thisistheconclusionofatwo-partseriesonJavacodingstyle.InGoodJavaStyle:Part1
,IintroducedmycaseforwritingJavacodeusinggoodhabits,explainedwhyweshouldcareaboutthewayourcodelooks,andillustratedsomegeneralelementsofgoodJavastyle.Inthispart,Iillustratemoreelementsofgoodstyleandbringmycasetoaconclusion.
SourceFiles
TherearemanywaysthataJavasourcefilecanbeorganized.Hereisonethatworkswell:
Fileheadercomment(optional).
Packagedeclaration.
Blanklineorotherseparator.
Importstatements.
Blanklineorotherseparator.
Class(es).
Example1.BadFileOrganization.
packageorg.rotpad;
importjava.awt.*;
importjavax.swing.event.*;
importorg.javacogs.*;
importjavax.swing.*;
importjava.awt.event.*;
classFoo{
...
}
publicclassRotPadextendsJFrame{
...
}
Example2.GoodFileOrganization.
packageorg.rotpad;
//Javaclasses
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
importjavax.swing.event.*;
//JavaCogsclasses
importorg.javacogs.*;
/**
*RotPadisasimpleGUIapplicationforperformingrotationciphersonplain
*text.
*
*@authorThorntonRose
*@version1.0
*/
publicclassRotPadextendsJFrame{
...
}
//-----------------------------------------------------------------------------
/**
*Foois...
*
*@authorThorntonRose
*@version1.0
*/
classFoo{
...
}
ImportStatements
Acomplexclasscanhavealargenumberofimports,whichcangetunruly,especiallyifyouprefertoimportindividualclassesinsteadofwholepackages(e.g.,java.awt.*).Togetahandleonimports,organizethemasfollows:
Javastandardclasses(java.*).
Javaextensionclasses(javax.*).
Third-partyclasses.
Applicationclasses.
Besuretocommentthethird-partyandapplicationclasses,particularlythosethatdonothaveobviousnames.Useend-of-linecomments,orputacommentatthebeginningofthesection.Also,ifyoureallywanttobeaperfectionist,ordereachgroupofimportsalphabetically.
Example3.BadImportStyle.
importjava.util.*;
importjavax.swing.*;
importjava.awt.event*;
importcom.gensym.com.*;
importjavax.swing.table.*;
importcom.pv.jfcx.*;
importjava.awt.*;
importcom.melthorn.util.*;
Example4a.GoodImportStyle.
importjava.awt.*;
importjava.awt.event*;
importjava.util.*;
importjavax.swing.table.*;
importcom.gensym.com.*;//BeanXporter
importcom.pv.jfcx.*;//ProtoView
importcom.melthorn.util.*;//Utilities
Example4b.GoodImportStyle.
//Javaclasses
importjava.awt.*;
importjava.awt.event*;
importjava.util.*;
importjavax.swing.table.*;
//BeanXporter
importcom.gensym.com.*;
//ProtoViewGUIcomponents
importcom.pv.jfcx.*;
//Applicationclasses
importcom.melthorn.util.*;
Classes
OrganizingaJavasourcefilewithoutorganizingtheclassesinitwouldnotgainyoumuchinthewayofproperstyle.Hereshowtoorganizetheclassesinyoursourcefiles:
Javadoccommentorotherheadercomment.
Classdeclaration.
Fielddeclarations.
Blanklineorotherseparator.
Constructors.
Blanklineorotherseparator.
Methods,exceptmain()
,groupedlogically.
Blanklineorotherseparator.
Innerclasses.
Blanklineorotherseparator.
main()
.
Example5.BadClassStyle.
//RotPad--GUIapp.forROTciphering
publicclassRotPadextendsJFrame{
privatestaticfinalStringTRANSFORM_ROT13="ROT13";
privatestaticfinalStringTRANSFORM_ROT13N5="ROT13N5";
privatestaticfinalStringTRANSFORM_ROTASCII="ROT-ASCII";
privatevoidjbInit()throwsException{
...
}
publicstaticfinalStringTITLE="RotPad";
publicstaticfinalStringVERSION="1.0";
publicstaticvoidmain(String[]args){
...
}
publicRotPad(){
...
}
privateJPaneljPanel1=newJPanel();
privateJPaneljPanel2=newJPanel();
privateBorderLayoutborderLayout1=newBorderLayout();
...
}
Example6.GoodClassStyle.
/**
*RotPadisasimpleGUIapplicationforperformingrotationciphersonplain
*text.
*
*@authorThorntonRose
*@version1.0
*/
publicclassRotPadextendsJFrame{
//Publicconstants
publicstaticfinalStringTITLE="RotPad";
publicstaticfinalStringVERSION="1.0";
//Privateconstants
privatestaticfinalStringTRANSFORM_ROT13="ROT13";
privatestaticfinalStringTRANSFORM_ROT13N5="ROT13N5";
privatestaticfinalStringTRANSFORM_ROTASCII="ROT-ASCII";
//GUIcomponents[JBuildergenerated]
privateBorderLayoutborderLayout1=newBorderLayout();
privateJPaneljPanel1=newJPanel();
privateJPaneljPanel2=newJPanel();
...
/**
*Constructanewinstanceofthisclass.
*/
publicRotPad(){
...
}
/**
*InitializeUIcomponents.[JBuildergenerated]
*/
privatevoidjbInit()throwsException{
...
}
...
//--------------------------------------------------------------------------
/**
*Starttheapplication.
*/
publicstaticvoidmain(String[]args){
...
}
}
FieldDeclarations
Someclasseshavealargenumberoffields,whichcanbecomedifficulttomaintainiftheyarenotorganizedwell.Organizethemasfollows:
Publiccontstants(finalandstaticfinal).
Publicvariables.
Protectedconstants.
Protectedvariables.
Packageconstants.
Packagevariables.
Privateconstants.
Privatevariables.
Additionally,usethefollowingguidelinesforwritingfielddeclarations:
Useonedeclarationperline.
UseJavadoccommentsonpublicandprotectedfields,atminimum.
UseUPPERCASEforthenamesofconstants.Usinguppercasemakesthemmuchmoreobviousinbothdeclarationsandexpressions.
Ifyouuseatoolthatgeneratesfielddeclarations,suchasJBuilderorVisualCafe,keepthegeneratedfieldsseparatefromtheotherfields.ItmakesmaintenanceoftheUIcodemucheasier.
Example7.BadFieldStyle.
publicclassCustomerSearchDialogextendsJDialog{
privateJLabelfirstNameLabel=newJLabel();
privateJLabellastNameLabel=newJLabel();
publicstaticfinalRESULT_SELECT=1;
privateVectorresults=newVector();//Searchresults.
privateDefaultTableModeltableModel=newDefaultTableModel();
publicstaticfinalRESULT_CANCEL=0;
//...
}
Example8.GoodFieldStyle.
/**
*...
*/
publicclassCustomerSearchDialogextendsJDialog{
/**
*Indicatesthatsearchwascancelled;returnedbyshowDialog()when
*userclickscancelbutton.
*/
publicstaticfinalRESULT_CANCEL=0;
/**
*Indicatesthatacustomerwasselected;returnedbyshowDialog()when
*userclicksselectbutton.
*/
publicstaticfinalRESULT_SELECT=1;
privateVectorresults=newVector();//Searchresults.
privateDefaultTableModeltableModel=newDefaultTableModel();//Gridmodel.
//GUIfields.[JBuilder]
privateJLabelfirstNameLabel=newJLabel();
privateJLabellastNameLabel=newJLabel();
//...
}
MethodDeclarations
Usethefollowingguidelinesforwritingmethoddeclarations:
AlwayshaveaJavadoccommentorsomeotherheadercomment.
Alwaysputtheaccessmodifierfirst.
Ifthelineistoolong,breakitintooneormorelines.
Ifthemethodhasmorethanafewparameters,considerputtingeachonaseparateline.
Dontputwhitespacebetweenthemethodnameandtheopeningparenthesis("(").
Alwaysputwhitespace(whichcouldbealinebreak)betweentheclosingparenthesis(")")andtheopeningbrace("{").
Example9.BadMethodStyle.
publicintgetTypeCount(StringcustType)
{
...
}
staticpublicgetInstance(){...};
publicvoidshowRange()
throwsRangeException{
...
}
Example10.GoodMethodStyles.
/**
*Returnthesingleinstanceofthisclass.
*/
publicstaticCalculationEnginegetInstance(){
returninstance;
}
/**
*Calculatetheconsumptioncoefficient.
*/
publicfloatcalculateConsumptionCoefficient(intbase,floatvariance,
intiterations)throwsRangeException{
//...
}
/**
*Calculatetheconsumptioncoefficient.
*/
publicfloatcalculateConsumptionCoefficient(
intbase,
floatvariance,
intiterations)
throwsRangeException
{
//...
}
/**
*Calculatetheconsumptioncoefficient.
*/
publicfloatcalculateConsumptionCoefficient(intbase,
floatvariance,
intiterations)
throwsRangeException
{
//...
}
Conclusion
Inconclusion,Ihaveonefinalthoughtforyouonthesubjectofcodestyle.Nomatterwhatguidelinesyoufollow,andnomatterhowferventyourbeliefsaboutthingslikeindentstyle(cf.,Raymond,"IndentStyle"),rememberthatwhenyouwritecodeyouroverallgoalshouldbetomakethecodeunderstandableandmaintainablebysomeoneelse.
RelatedLinks
IndentStyle,TheJargonFile,EricS.Raymond.
Tabsvs.Spaces,JamieZawinski.
WritingRobustJavaCode―TheAmbysoftInc.CodingStandardsforJava,ScottAmbler.
DraftJavaCodingStandard,DougLea.
JavaCodeConventions,SunMicrosystems,Inc.
HowtoWriteDocCommentsforJavadoc,SunMicrosystems,Inc.
TheJargonFile(knowninprintasTheNewHackersDictionary),EricS.Raymond.
AbouttheAuthor
ThorntonRoseisacontractsoftwaredeveloperinAtlanta,Ga.Hecanbereachedviae-mailatthornton.rose@mindspring.com.
java也能做一些底层语言开发做的事情(难度很高,不是java顶尖高手是做不来的), |
|