We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 17
JAVA CODING STANDARDS
Purpose of this document
This document describes a collection of standards, conventions and guidelines for writing Java code that is easy to understand, to maintain, and to enhance. Important features of this document Existing standards from the industry are used wherever possible The reason behind each standard is explained so that developers can understand why they should follow it. These standards are based on proven software-engineering principles that lead to improved development productivity, greater maintainability, and greater scalability. Target Audience Professional Software developers who are involved in !riting Java code that is easy to maintain and to enhance "ncreasing their productivity Why coding standards are important #oding standards for Java are important because they lead to greater consistency within code of all developers. #onsistency leads to code that is easier to understand, which in turn results in a code, which is easier to develop and maintain. #ode that is difficult to understand and maintain runs the ris$ of being scrapped and rewritten. The Prime Directive % pro&ect re'uirement may vary from the standards mentioned in this document. When going against the standards, projects should a!e sure to docuent it" 1. Naming Convention #se $ull %nglish descriptors that accuratel& descri'e the (aria'le)$ield)class)inter$ace (or example, use names li$e $irstNae, grandTotal, or CorporateCustoer. #se terinolog& applica'le to the doain "f the users of the system refer to their clients as #ustomer, then use the term #ustomer for the class, not client. #se i*ed case to a!e naes reada'le #se a''re(iations sparingl&, 'ut i$ &ou do so then use then intelligentl& and docuent it (or example, to use a short form for the word )number*, choose one of n'r, no or nu. A(oid long naes +,-. characters is a good tradeo$$/ A(oid naes that are siilar or di$$er onl& in case 2. Documentation Coents should add to the clarit& o$ code" A(oid decoration, i"e", do not use 'anner0li!e coents Docuent 1h& soething is 'eing done, not just 1hat" Java Comments Coent T&pe #sage %*aple Docuentation Starts with +,, and ends with ,+ -sed before declarations of interfaces, classes, member functions, and fields to document them. +,, , #ustomer . a person or , organi/ation ,+ C st&le Starts with +, and ends with ,+ -sed to document out lines of code that are no longer applicable. "t is helpful in debugging. +, This code was commented out by %shish Sarin ,+ Single line Starts with ++ and go until the end of the line -sed internally within member functions to document business logic, sections of code, and declarations of temporary variables. )) "f the amount is greater ++ than 01 multiply by 011 3. Standards For Member Functions 3. 1 Naming member functions 2ember functions should be named using a full English description, using mixed case with the first letter of any non-initial word capitali/ed. The first word of the member function should be a verb. %*aples open%ccount34 print2ailing5ist34 save34 delete34 This results in member functions whose purpose can be determined &ust by loo$ing at its name. 3.1.1 Naming ccessor Member Functions 3.1.1.1 !etters" member functions that return the value of a field + attribute + property of an ob&ect. -se prefix )get* to the name of the field + attribute + property if the field in not boolean -se prefix )is* to the name of the field + attribute + property if the field is 6oolean % viable alternative is to use the prefix 7has8 or 7can8 instead of 7is8 for boolean getters. %*aples get(irst9ame34 isPersistent34 3.1.1.2 Setters" member functions that modify the values of a field. -se prefix 7set8 to the name of the field. %*aples set(irst9ame34 3.1.1.3 Constructors" member functions that perform any necessary initiali/ation when an ob&ect is created. #onstructors are always given the same name as their class. %*aples #ustomer34 Savings%ccount34 3.2 Member Function #isibi$it% % good design re'uires minimum coupling between the classes. The general rule is to be as restrictive as possible when setting the visibility of a member function. "f member function doesn8t have to be public then ma$e it protected, and if it doesn8t have to be protected than ma$e it private. 3.3 Documenting Member Functions 3.3.1 Member Function &eader 2ember function documentation should include the following !hat and why the member function does what it does !hat member function must be passed as parameters !hat a member function returns :nown bugs %ny exception that a member function throws ;isibility decisions 3if 'uestionable by other developers4 <ow a member function changes the ob&ect . it is to helps a developer to understand how a member function invocation will affect the target ob&ect. "nclude a history of any code changes Examples of how to invo$e the member function if appropriate. %pplicable pre conditions and post conditions under which the function will wor$ properly. These are the assumptions made during writing of the function. %ll concurrency issues should be addressed. - Explanation of why $eeping a function synchroni/ed must be documented. !hen a member function updates a field+attribute+property, of a class that implements the Runna'le interface, is not synchroni/ed then it should be documented why it is unsynchroni/ed. "f a member function is overloaded or overridden or synchroni/ation changed, it should also be documented. Note2 "t8s not necessary to document all the factors described above for each and every member function because not all factors are applicable to every member function. 3.3.2 'nterna$ Documentation" #omments within the member functions -se # style comments to document out lines of unneeded code. -se single-line comments for business logic. "nternally following should be documented Control Structures This includes comparison statements and loops Wh&, as 1ell as 1hat, the code does 3ocal (aria'les Di$$icult or cople* code The processing order "f there are statements in the code that must be executed in a defined order 3.3.3 Document the c$osing braces "f there are many control structures one inside another (.) Techni*ues for +riting C$ean Code" Docuent the code %lready discussed above 4aragraph)Indent the code2 %ny code between the = and > should be properly indented 4aragraph and punctuate ulti0line stateents %*aple 5ine 0 6an$%ccount newPersonal%ccount ? %ccount(actory 5ine @ create6an$%ccount(or3current#ustomer, startAate, 5ine B initialAeposit, branch4 5ines @ C B have been indented by one unit 3hori/ontal tab4 #se 1hite space % few blan$ lines or spaces can help ma$e the code more readable. Single blan$ lines to separate logical groups of code, such as control structures Two blan$ lines to separate member function definitions Speci$& the order o$ Operations2 -se extra parenthesis to increase the readability of the code using %9A and DE comparisons. This facilitates in identifying the exact order of operations in the code Write short, single coand lines #ode should do one operation per line So only one statement should be there per line ,.) Standards for Fie$ds -ttributes . Pro/erties0 ,.1 Naming Fie$ds #se a 5ull %nglish Descriptor $or 5ield Naes (ields that are collections, such as arrays or vectors, should be given names that are plural to indicate that they represent multiple values. %*aples first9ame order"tems "f the name of the field begins with an acronym then the acronym should be completely in lower case %*aple s'lAatabase ,.2 Naming Com/onents -se full English descriptor postfixed by the widget type. This ma$es it easy for a developer to identify the purpose of the components as well as its type. %*aple o$6utton customer5ist file2enu new(ile2enu"tem ,.3 Naming Constants "n Java, constants, values that do not change, are typically implemented as static final fields of classes. The convention is to use full English words, all in upper case, with underscores between the words %*aple 2"9"2-2F6%5%9#E 2%GF;%5-E AE(%-5TFST%ETFA%TE 0 ,.( Fie$d #isibi$it% (ields should not be declared public for reasons of encapsulation. %ll fields should be declared private and accessor methods should be used to access + modify the field value. This results in less coupling between classes as the protected + public + pac$age access of field can result in direct access of the field from other classes ,., Documenting a Fie$d Aocument the following It6s description Docuent all applica'le in(ariants "nvariants of a field are the conditions that are always true about it. 6y documenting the restrictions on the values of a field one can understand important business rules, ma$ing it easier to understand how the code wor$s + how the code is supposed to wor$ %*aples (or fields that have complex business rules associated with them one should provide several example values so as to ma$e them easier to understand Concurrenc& issues Visi'ilit& decisions "f a field is declared anything but private then it should be documented why it has not been declared private. ,.1 2sage of ccesors %ccessors can be used for more than &ust getting and setting the values of instance fields. %ccesors should be used for following purpose also Initiali7e the (alues o$ $ields -se la/y initiali/ation where fields are initiali/ed by their getter member functions. %*aple )88 8 %nswer the branch number, which is the leftmost four digits of the full account 8 number. %ccount numbers are in the format 6666%%%%%%. 8) protected int get6ranch9umber34 = if3branch9umber ?? 14 = ++ The default branch number is 0111, which is the ++ main branch in downtown 6edroc$ set6ranch9umber301114H > 0 Java #oding Standards return branch9umberH > Note2 This approach is advantageous for ob&ects that have fields that aren8t regularly accessed !henever la/y initiali/ation is used in a getter function the programmer should document what is the type of default value, what the default value as in the example above. ,.1.1 ccess constant va$ues #ommonly constant values are declared as static final fields. This approach ma$es sense for )constants* that are stable. "f the constants can change because of some changes in the business rules as the business matures then it is better to use getter member functions for constants. 6y using accesors for constants programmer can decrease the chance of bugs and at the same time increase the maintainability of the system. ,.1.2 ccess Co$$ections The main purpose of accesors is to encapsulate the access to fields so as to reduce the coupling within the code. #ollections, such as arrays and vectors, being more complex than single value fields have more than &ust standard getter and setter member function implemented for them. 6ecause the business rule may re'uire to add and remove to and from collections, accessor member functions need to be included to do so. %*aple Member function t%/e Naming Convention 34am/$e Ietter for the collection get#ollection34 getDrder"tems34 Setter for the collection set#ollection34 setDrder"tems34 "nsert an ob&ect into the collection insertDb&ect34 insertDrder"tems34 Aelete an ob&ect from the collection deleteDb&ect34 deleteDrder"tems34 #reate and add a new ob&ect into the collection newDb&ect34 newDrder"tem34 Note The advantage of this approach is that the collection is fully encapsulated, allowing programmer to later replace it with another structure "t is common to that the getter member functions be public and the setter be protected Al1a&s Initiali7e Static 5ields because one can8t assume that instances of a class will be created before a static field is accessed 1.) Standards for 5oca$ #ariab$es 1.1 Naming 5oca$ #ariab$es -se full English descriptors with the first letter of any non-initial word in uppercase. 1.1.1 Naming Streams !hen there is a single input and+or output stream being opened, used, and then closed within a member function the convention is to use in and out for the names of these streams, respectively. 1.1.2 Naming 5oo/ Counters % common way is to use words li$e loopCounters or simply counter because it helps facilitate the search for the counters in the program. i, j, ! can also be used as loop counters but the disadvantage is that search for i ,& and $ in the code will result in many hits. 1.1.3 Naming 34ce/tion 6b7ects The use of letter e for a generic exception 1.2 Dec$aring and Documenting 5oca$ #ariab$es Aeclare one local variable per line of code Aocument local variable with an endline comment Aeclare local variables immediately before their use -se local variable for one operation only. !henever a local variable is used for more than one reason, it effectively decreases its cohesion, ma$ing it difficult to understand. "t also increases the chances of introducing bugs into the code from unexpected side effects of previous values of a local variable from earlier in the code. Note Eeusing local variables is more efficient because less memory needs to be allocated, but reusing local variables decreases the maintainability of code and ma$es it more fragile 8.) Standards for Parameters -rguments0 to Member Functions 8.1 Naming Parameters Parameters should be named following the exact same conventions as for local variable Name /arameters the same as their corres/onding fie$ds -if an%0 %*aple "f Account has an attribute called 'alance and you needed to pass a parameter representing a new value for it the parameter would be called 'alance The field would be referred to as this"'alance in the code and the parameter would be referred as 'alance 8.2 Documenting Parameters Parameters to a member function are documented in the header documentation for the member function using the javadoc @param tag. "t should describe !hat it should be used for %ny restrictions or preconditions Examples "f it is not completely obvious what a parameter should be, then it should provide one or more examples in the documentation Note -se interface as a parameter to the member function then the ob&ect itself. Standards for C$asses9 'nterfaces9 Pac:ages9 and Com/i$ation 2nits ;.) Standards for C$asses ;.1 C$ass #isibi$it% -se pac$age visibility for classes internal to a component -se public visibility for the faJade of components ;.2 Naming c$asses -se full English descriptor starting with the first letter capitali/ed using mixed case for the rest of the name ;.3 Documenting a C$ass The purpose of the class :nown bugs The development+maintenance history of the class Aocument applicable variants The concurrency strategy %ny class that implements the interface Runna'le should have its concurrency strategy fully described ;.( 6rdering Member Functions and Fie$ds The order should be #onstructors private fields public member functions protected member functions private member functions finali/e34 <.) Standards for 'nterfaces <.1 Naming 'nterfaces 9ame interfaces using mixed case with the first letter of each word capitali/ed. Prefix the letter )"* or )"fc* to the interface name <.2 Documenting 'nterfaces The Purpose <ow it should and shouldn8t be used 1).) Standards for Pac:ages 5ocal pac$ages names begin with an identifier that is not all upper case Ilobal pac$age names begin with the reversed "nternet domain name for the organi/ation Pac$age names should be singular 1).1 Documenting a Pac:age The rationale for the pac$age The classes in the pac$ages 11.) Standards for Com/i$ation 2nit -Source code fi$e0 11.1 Naming a Com/i$ation 2nit % compilation unit should be given the name of the primary class or interface that is declared within it. -se the same name of the class for the file name, using the same case. 11.2 =eginning Comments +,, , #lassname , , ;ersion information , , Aate , , #opyright notice ,+ 11.3 Dec$aration #lass+interface documentation comment See Aocumentation standard for class + 3+,,...,+4 interfaces #lass or interface statement #lass+interface implementation comment 3+,...,+4, if necessary This comment should contain any class-wide or interface-wide information that wasnKt appropriate for the class+interface documentation comment. #lass 3static4 variables (irst the public class variables, then the protected, then pac$age level 3no access modifier4, and then the private. "nstance variables (irst public, then protected, then pac$age level 3no access modifier4, and then private. 2ethods These methods should be grouped by functionality rather than by scope or accessibility. (or example, a private class method can be in between two public instance methods. The goal is to ma$e reading and understanding the code easier. 11.( 'ndentation (our spaces should be used as the unit of indentation. The exact construction of the indentation 3spaces vs. tabs4 is unspecified. Tabs must be set exactly every L spaces 3not M4.
11., 5ine 5ength %void lines longer than L1 characters, since theyKre not handled well by many terminals and tools. Note2 Examples for use in documentation should have a shorter line length-generally no more than N1 characters. 11., +ra//ing 5ines !hen an expression will not fit on a single line, brea$ it according to these general principles
6rea$ after a comma. 6rea$ before an operator. Prefer higher-level brea$s to lower-level brea$s. %lign the new line with the beginning of the expression at the same level on the previous line. "f the above rules lead to confusing code or to code thatKs s'uished up against the right margin, &ust indent L spaces instead. <ere are some e*aples of brea$ing method calls some2ethod3longExpression0, longExpression@, longExpressionB, longExpressionM, longExpressionO4H var ? some2ethod03longExpression0, some2ethod@3longExpression@, longExpressionB44H (ollowing are two examples of brea$ing an arithmetic expression. The first is preferred, since the brea$ occurs outside the parenthesi/ed expression, which is at a higher level. long9ame0 ? long9ame@ , 3long9ameB P long9ameM - long9ameO4 P M , longnameQH ++ PEE(EE long9ame0 ? long9ame@ , 3long9ameB P long9ameM - long9ameO4 P M , longnameQH ++ %;D"A (ollowing are two examples of indenting method declarations. The first is the conventional case. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only L spaces. ++#D9;E9T"D9%5 "9AE9T%T"D9 some2ethod3int an%rg, Db&ect another%rg, String yet%nother%rg, Db&ect andStill%nother4 = ... > ++"9AE9T L SP%#ES TD %;D"A ;EER AEEP "9AE9TS private static synchroni/ed hor$ing5ong2ethod9ame3int an%rg, Db&ect another%rg, String yet%nother%rg, Db&ect andStill%nother4 = ... > 5ine wrapping for if statements should generally use the L-space rule, since conventional 3M space4 indentation ma$es seeing the body difficult. (or example ++AD9KT -SE T<"S "9AE9T%T"D9 if 33condition0 CC condition@4 SS 3conditionB CC conditionM4 SST3conditionO CC conditionQ44 = ++6%A !E%PS doSomething%bout"t34H ++2%:E T<"S 5"9E E%SR TD 2"SS > ++-SE T<"S "9AE9T%T"D9 "9STE%A if 33condition0 CC condition@4 SS 3conditionB CC conditionM4 SST3conditionO CC conditionQ44 = doSomething%bout"t34H > ++DE -SE T<"S if 33condition0 CC condition@4 SS 3conditionB CC conditionM4 SST3conditionO CC conditionQ44 = doSomething%bout"t34H > <ere are three acceptable ways to format ternary expressions alpha ? 3a5ong6ooleanExpression4 U beta gammaH alpha ? 3a5ong6ooleanExpression4 U beta gammaH alpha ? 3a5ong6ooleanExpression4 U beta gammaH 11.1 Dec$aration Dne declaration per line is recommended since it encourages commenting. "n other words, int levelH ++ indentation level int si/eH ++ si/e of table is preferred over int level, si/eH Ao not put different types on the same line. Example int foo, fooarrayVWH ++!ED9IT Note2 The examples above use one space between the type and the identifier. %nother acceptable alternative is to use tabs, e.g. int levelH ++ indentation level int si/eH ++ si/e of table Db&ect currentEntryH ++ currently selected table entry 11.8 'nitia$i>ation Try to initiali/e local variables where theyKre declared. The only reason not to initiali/e a variable where itKs declared is if the initial value depends on some computation occurring first. 11.; P$acement Put declarations only at the beginning of bloc$s. 3% bloc$ is any code surrounded by curly braces X=X and X>X.4 AonKt wait to declare variables until their first useH it can confuse the unwary programmer and hamper code portability within the scope. void my2ethod34 = int int0 ? 1H ++ beginning of method bloc$ if 3condition4 = int int@ ? 1H ++ beginning of XifX bloc$ ... > > The one exception to the rule is indexes of for loops, which in Java can be declared in the for statement for 3int i ? 1H i Y max5oopsH iPP4 = ... > %void local declarations that hide declarations at higher levels. (or example, do not declare the same variable name in an inner bloc$ int countH ... my2ethod34 = if 3condition4 = int count ? 1H ++ %;D"AT ... > ... > 11.< C$ass and 'nterface Dec$arations !hen coding Java classes and interfaces, the following formatting rules should be followed 9o space between a method name and the parenthesis X3X starting its parameter list Dpen brace X=X appears at the end of the same line as the declaration statement #losing brace X>X starts a line by itself indented to match its corresponding opening statement, except when it is a null statement the X>X should appear immediately after the X=X class Sample extends Db&ect = int ivar0H int ivar@H Sample3int i, int &4 = ivar0 ? iH ivar@ ? &H > int empty2ethod34 => ... > A 'lan! line separates ethods 11.1) Statements Siple Stateents Each line should contain at most one statement. %*aple2 argvPPH ++ #orrect argc--H ++ #orrect argvPPH argc--H ++ %;D"AT Copound Stateents #ompound statements are statements that contain lists of statements enclosed in braces X= statements >X. See the following sections for examples. The enclosed statements should be indented one more level than the compound statement. The opening brace should be at the end of the line that begins the compound statementH the closing brace should begin a line and be indented to the beginning of the compound statement. 6races are used around all statements, even single statements, when they are part of a control structure, such as a if-else or for statement. This ma$es it easier to add statements without accidentally introducing bugs due to forgetting to add braces. return Stateents % return statement with a value should not use parentheses unless they ma$e the return value more obvious in some way. %*aple2 returnH return myAis$.si/e34H return 3si/e U si/e defaultSi/e4H i$, i$0else, i$ else0i$ else Stateents The if-else class of statements should have the following form if 3condition4 = statementsH > if 3condition4 = statementsH > else = statementsH > if 3condition4 = statementsH > else if 3condition4 = statementsH > else = statementsH >
Note2 if statements always use braces =>. %void the following error-prone form if 3condition4 ++%;D"AT T<"S D2"TS T<E 6E%#ES =>T statementH $or Stateents % for statement should have the following form for 3initializationH conditionH update4 = statementsH > %n empty for statement 3one in which all the wor$ is done in the initiali/ation, condition, and update clauses4 should have the following form for 3initializationH conditionH update4H !hen using the comma operator in the initiali/ation or update clause of a for statement, avoid the complexity of using more than three variables. "f needed, use separate statements before the for loop 3for the initiali/ation clause4 or at the end of the loop 3for the update clause4. 1hile Stateents % while statement should have the following form while 3condition4 = statementsH > %n empty while statement should have the following form while 3condition4H do01hile Stateents % do-while statement should have the following form do = statementsH > while 3condition4H s1itch Stateents % switch statement should have the following form switch 3condition4 = case %6# statementsH +, falls through ,+ case AE( statementsH brea$H case GRZ statementsH brea$H default statementsH brea$H > Every time a case falls through 3doesnKt include a brea$ statement4, add a comment where the brea$ statement would normally be. This is shown in the preceding code example with the +, falls through ,+ comment. Every switch statement should include a default case. The brea$ in the default case is redundant, but it prevents a fall-through error if later another case is added. tr&0catch Stateents % try-catch statement should have the following format try = statementsH > catch 3Exception#lass e4 = statementsH > % try-catch statement may also be followed by finally, which executes regardless of whether or not the try bloc$ has completed successfully. try = statementsH > catch 3Exception#lass e4 = statementsH > finally = statements; > 9lan! 3ines 6lan$ lines improve readability by setting off sections of code that are logically related. Two blan$ lines should always be used in the following circumstances 6etween sections of a source file 6etween class and interface definitions Dne blan$ line should always be used in the following circumstances 6etween methods 6etween the local variables in a method and its first statement 6efore a bloc$ or single-line comment 6etween logical sections inside a method to improve readability 9lan! Spaces 6lan$ spaces should be used in the following circumstances % $eyword followed by a parenthesis should be separated by a space. Example while 3true4 = ... > 9ote that a blan$ space should not be used between a method name and its opening parenthesis. This helps to distinguish $eywords from method calls. % blan$ space should appear after commas in argument lists. %ll binary operators except . should be separated from their operands by spaces. 6lan$ spaces should never separate unary operators such as unary minus, increment 3XPPX4, and decrement 3X--X4 from their operands. %*aple2 a P? c P dH a ? 3a P b4 + 3c , d4H
while 3dPP ? sPP4 = nPPH > printSi/e3Xsi/e is X P foo P X[nX4H The expressions in a for statement should be separated by blan$ spaces. Example for 3expr0H expr@H exprB4 #asts should be followed by a blan$ space. Examples my2ethod33byte4 a9um, 3Db&ect4 x4H my2ethod33int4 3cp P O4, 33int4 3i P B44 P 04H Naing Con(entions Suar& Identi$ier T&pe Rules $or Naing %*aples 4ac!ages The prefix of a uni'ue pac$age name is always written in all-lowercase %S#"" letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying com.sun.eng com.apple.'uic$time.v@ edu.cmu.cs.bovi$.cheese countries as specified in "SD Standard B0QQ, 0\L0. Subse'uent components of the pac$age name vary according to an organi/ationKs own internal naming conventions. Such conventions might specify that certain directory name components be division, department, pro&ect, machine, or login names. Classes #lass names should be nouns, in mixed case with the first letter of each internal word capitali/ed. Try to $eep your class names simple and descriptive. -se whole words- avoid acronyms and abbreviations 3unless the abbreviation is much more widely used than the long form, such as -E5 or <T254. class EasterH class "mageSpriteH Inter$aces "nterface names should be capitali/ed li$e class names. interface EasterAelegateH interface StoringH :ethods 2ethods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitali/ed. run34H run(ast34H get6ac$ground34H Varia'les Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. "nternal words start with capital letters. ;ariable names should not start with underscore F or dollar sign ] characters, even though @ both are allowed. ;ariable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. Dne-character variable names should be avoided except for temporary XthrowawayX variables. int iH char cH float my!idthH @ Java #oding Standards #ommon names for temporary variables are i, &, $, m, and n for integersH c, d, and e for characters. Constants The names of variables declared class constants and of %9S" constants should be all uppercase with words separated by underscores 3XFX4. 3%9S" constants should be avoided, for ease of debugging.4 static final int 2"9F!"AT< ? MH static final int 2%GF!"AT< ? \\\H static final int IETFT<EF#P- ? 0H Re$erences2 www.&ava.sun.com