76829060 java-coding-conventions


Published on

Published in: Education, Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

76829060 java-coding-conventions

  1. 1. JAVA CODING STANDARDSPurpose of this documentThis document describes a collection ofstandards, conventions and guidelines forwriting Java code that is easy to understand,to maintain, and to enhance.Important features of this documentExisting standards from the industry areused wherever possibleThe reason behind each standard isexplained so that developers can understandwhy they should follow it.These standards are based on provensoftware-engineering principles that lead toimproved development productivity, greatermaintainability, and greater scalability.Target Audience
  2. 2. Professional Software developers who areinvolved in:Writing Java code that is easy to maintainand to enhanceIncreasing their productivityWhy coding standards are importantCoding standards for Java are importantbecause they lead to greater consistencywithin code of all developers. Consistencyleads to code that is easier to understand,which in turn results in a code, which iseasier to develop and maintain. Code that isdifficult to understand and maintain runs therisk of being scrapped and rewritten.The Prime DirectiveA project requirement may vary from thestandards mentioned in this document.
  3. 3. When going against the standards,projects should make sure to document it.1. Naming ConventionUse full English descriptors thataccurately describe thevariable/field/class/interfaceFor example, use names like firstName,grandTotal, or CorporateCustomer.Use terminology applicable to the domainIf the users of the system refer to theirclients as Customer, then use the termCustomer for the class, not client.Use mixed case to make names readableUse abbreviations sparingly, but if you doso then use then intelligently anddocument it
  4. 4. For example, to use a short form for theword “number”, choose one of nbr, no ornum.Avoid long names (<15 characters is agood tradeoff)Avoid names that are similar or differonly in case2. DocumentationComments should add to the clarity ofcode.Avoid decoration, i.e., do not use banner-like commentsDocument why something is being done,not just what.Java CommentsComment Usage Example
  5. 5. TypeDocumentation Used before /** declarations * CustomerStarts with /** of interfaces, – a person orand ends with classes, **/ member organization functions, */ and fields to document them.C style Used to /* document This codeStarts with /* out lines of wasand ends with code that are commented*/ no longer out by applicable. It Ashish Sarin is helpful in */ debugging.Single line Used // If the internally amount isStarts with // within greaterand go until the member // than 10
  6. 6. end of the line functions to multiply by document 100 business logic, sections of code, and declarations of temporary variables.3. Standards For Member Functions3. 1 Naming member functionsMember functions should be named using afull English description, using mixed casewith the first letter of any non-initial wordcapitalized. The first word of the memberfunction should be a verb.ExamplesopenAccount()printMailingList()save()
  7. 7. delete()This results in member functions whosepurpose can be determined just by looking atits name.3.1.1 Naming Accessor Member Functions3.1.1.1 Getters: member functions thatreturn the value of a field / attribute /property of an object.Use prefix “get” to the name of the field /attribute / property if the field in not booleanUse prefix “is” to the name of the field /attribute / property if the field is BooleanA viable alternative is to use the prefix ‘has’or ‘can’ instead of ‘is’ for boolean getters.ExamplesgetFirstName()isPersistent()
  8. 8. Setters: member functions thatmodify the values of a field.Use prefix ‘set’ to the name of the field.ExamplessetFirstName() Constructors: member functions thatperform any necessary initialization when anobject is created. Constructors are alwaysgiven the same name as their class.ExamplesCustomer()SavingsAccount()3.2 Member Function VisibilityA good design requires minimum couplingbetween the classes. The general rule is tobe as restrictive as possible when setting the
  9. 9. visibility of a member function. If memberfunction doesn’t have to be public thenmake it protected, and if it doesn’t have tobe protected than make it private.3.3 Documenting Member Functions3.3.1 Member Function HeaderMember function documentation shouldinclude the following:What and why the member function doeswhat it doesWhat member function must be passed asparametersWhat a member function returnsKnown bugsAny exception that a member functionthrowsVisibility decisions (if questionable by otherdevelopers)How a member function changes the object– it is to helps a developer to understand
  10. 10. how a member function invocation willaffect the target object.Include a history of any code changesExamples of how to invoke the memberfunction if appropriate.Applicable pre conditions and postconditions under which the function willwork properly. These are the assumptionsmade during writing of the function.All concurrency issues should be addressed.- Explanation of why keeping a functionsynchronized must be documented.When a member function updates afield/attribute/property, of a class thatimplements the Runnable interface, is notsynchronized then it should be documentedwhy it is unsynchronized.If a member function is overloaded oroverridden or synchronization changed, itshould also be documented.Note: It’s not necessary to document all thefactors described above for each and every
  11. 11. member function because not all factors areapplicable to every member function.3.3.2 Internal Documentation: Commentswithin the member functionsUse C style comments to document out linesof unneeded code.Use single-line comments for business logic.Internally following should be documented:Control Structures This includescomparison statements and loopsWhy, as well as what, the code doesLocal variablesDifficult or complex codeThe processing order If there arestatements in the code that must be executedin a defined order
  12. 12. 3.3.3 Document the closing braces If thereare many control structures one insideanother4.0 Techniques for Writing Clean Code:Document the code Already discussedaboveParagraph/Indent the code: Any codebetween the { and } should be properlyindentedParagraph and punctuate multi-linestatementsExampleLine 1 BankAccount newPersonalAccount= AccountFactoryLine 2createBankAccountFor(currentCustomer,startDate,
  13. 13. Line 3 initialDeposit, branch)Lines 2 & 3 have been indented by one unit(horizontal tab)Use white spaceA few blank lines or spaces can help makethe code more readable.Single blank lines to separate logical groupsof code, such as control structuresTwo blank lines to separate memberfunction definitionsSpecify the order of Operations: Use extraparenthesis to increase the readability of thecode using AND and OR comparisons. Thisfacilitates in identifying the exact order ofoperations in the code
  14. 14. Write short, single command lines Codeshould do one operation per line So only onestatement should be there per line5.0 Standards for Fields (Attributes /Properties)5.1 Naming FieldsUse a Full English Descriptor for FieldNamesFields that are collections, such as arrays orvectors, should be given names that areplural to indicate that they represent multiplevalues.ExamplesfirstNameorderItems
  15. 15. If the name of the field begins with anacronym then the acronym should becompletely in lower caseExamplesqlDatabase5.2 Naming ComponentsUse full English descriptor postfixed by thewidget type. This makes it easy for adeveloper to identify the purpose of thecomponents as well as its type.ExampleokButtoncustomerListfileMenunewFileMenuItem
  16. 16. 5.3 Naming ConstantsIn Java, constants, values that do not change,are typically implemented as static finalfields of classes. The convention is to usefull English words, all in upper case, withunderscores between the wordsExampleMINIMUM_BALANCEMAX_VALUEDEFAULT_START_DATE15.4 Field VisibilityFields should not be declared public forreasons of encapsulation. All fields shouldbe declared private and accessor methodsshould be used to access / modify the fieldvalue. This results in less coupling betweenclasses as the protected / public / package1 Java Coding Standards
  17. 17. access of field can result in direct access ofthe field from other classes5.5 Documenting a FieldDocument the following:It’s descriptionDocument all applicable invariantsInvariants of a field are the conditions thatare always true about it. By documenting therestrictions on the values of a field one canunderstand important business rules, makingit easier to understand how the code works /how the code is supposed to workExamples For fields that have complexbusiness rules associated with them oneshould provide several example values so asto make them easier to understandConcurrency issuesVisibility decisions If a field is declaredanything but private then it should be
  18. 18. documented why it has not been declaredprivate.5.6 Usage of Accesors Accessors can beused for more than just getting and settingthe values of instance fields. Accesorsshould be used for following purpose also:Initialize the values of fields Use lazyinitialization where fields are initialized bytheir getter member functions.Example/** * Answer the branch number, which is theleftmost four digits of the full account * number. Account numbers are in theformat BBBBAAAAAA. */protected int getBranchNumber(){ if(branchNumber == 0) {
  19. 19. // The default branch number is1000, which is the // main branch in downtown Bedrock setBranchNumber(1000); } return branchNumber;}Note:This approach is advantageous for objectsthat have fields that aren’t regularlyaccessedWhenever lazy initialization is used in agetter function the programmer shoulddocument what is the type of default value,what the default value as in the exampleabove.5.6.1 Access constant values Commonlyconstant values are declared as static finalfields. This approach makes sense for“constants” that are stable.
  20. 20. If the constants can change because of somechanges in the business rules as the businessmatures then it is better to use gettermember functions for constants.By using accesors for constants programmercan decrease the chance of bugs and at thesame time increase the maintainability of thesystem.5.6.2 Access Collections The main purposeof accesors is to encapsulate the access tofields so as to reduce the coupling within thecode. Collections, such as arrays andvectors, being more complex than singlevalue fields have more than just standardgetter and setter member functionimplemented for them. Because the businessrule may require to add and remove to andfrom collections, accessor member functionsneed to be included to do so.Example Member Naming Example
  21. 21. function ConventiontypeGetter for getCollection() getOrderItems()thecollectionSetter for setCollection() setOrderItems()thecollectionInsert an insertObject() insertOrderItems()objectinto thecollectionDelete an deleteObject() deleteOrderItems()objectfrom thecollectionCreate newObject() newOrderItem()and add anewobjectinto thecollection
  22. 22. NoteThe advantage of this approach is that thecollection is fully encapsulated, allowingprogrammer to later replace it with anotherstructureIt is common to that the getter memberfunctions be public and the setter beprotectedAlways Initialize Static Fields because onecan’t assume that instances of a class will becreated before a static field is accessed6.0 Standards for Local Variables6.1 Naming Local VariablesUse full English descriptors with the firstletter of any non-initial word in uppercase.6.1.1 Naming StreamsWhen there is a single input and/or outputstream being opened, used, and then closedwithin a member function the convention is
  23. 23. to use in and out for the names of thesestreams, respectively.6.1.2 Naming Loop CountersA common way is to use words likeloopCounters or simply counter because ithelps facilitate the search for the counters inthe program.i, j, k can also be used as loop counters butthe disadvantage is that search for i ,j and kin the code will result in many hits.6.1.3 Naming Exception ObjectsThe use of letter e for a generic exception6.2 Declaring and Documenting LocalVariablesDeclare one local variable per line of codeDocument local variable with an endlinecommentDeclare local variables immediately beforetheir use
  24. 24. Use local variable for one operation only.Whenever a local variable is used for morethan one reason, it effectively decreases itscohesion, making it difficult to understand.It also increases the chances of introducingbugs into the code from unexpected sideeffects of previous values of a local variablefrom earlier in the code.NoteReusing local variables is more efficientbecause less memory needs to be allocated,but reusing local variables decreases themaintainability of code and makes it morefragile7.0 Standards for Parameters (Arguments)to Member Functions7.1 Naming ParametersParameters should be named following theexact same conventions as for local variable
  25. 25. Name parameters the same as theircorresponding fields (if any)ExampleIf Account has an attribute called balanceand you needed to pass a parameterrepresenting a new value for it the parameterwould be called balance The field would bereferred to as this.balance in the code andthe parameter would be referred as balance7.2 Documenting ParametersParameters to a member function aredocumented in the header documentation forthe member function using the javadoc@param tag. It should describe:What it should be used forAny restrictions or preconditionsExamples If it is not completely obviouswhat a parameter should be, then it shouldprovide one or more examples in thedocumentation
  26. 26. NoteUse interface as a parameter to the memberfunction then the object itself.Standards for Classes, Interfaces,Packages, and Compilation Units8.0 Standards for Classes8.1 Class VisibilityUse package visibility for classes internal toa componentUse public visibility for the façade ofcomponents8.2 Naming classesUse full English descriptor starting with thefirst letter capitalized using mixed case forthe rest of the name8.3 Documenting a Class
  27. 27. The purpose of the classKnown bugsThe development/maintenance history of theclassDocument applicable variantsThe concurrency strategy Any class thatimplements the interface Runnable shouldhave its concurrency strategy fully described8.4 Ordering Member Functions andFieldsThe order should be:Constructorsprivate fieldspublic member functions protected member functions private member functionsfinalize()9.0 Standards for Interfaces9.1 Naming Interfaces
  28. 28. Name interfaces using mixed case with thefirst letter of each word capitalized.Prefix the letter “I” or “Ifc” to the interfacename9.2 Documenting InterfacesThe PurposeHow it should and shouldn’t be used10.0 Standards for Packages Local packages names begin with anidentifier that is not all upper caseGlobal package names begin with thereversed Internet domain name for theorganizationPackage names should be singular10.1 Documenting a Package The rationale for the package The classes in the packages
  29. 29. 11.0 Standards for Compilation Unit(Source code file)11.1 Naming a Compilation UnitA compilation unit should be given thename of the primary class or interface that isdeclared within it. Use the same name of theclass for the file name, using the same case.11.2 Beginning Comments /** * Classname * * Version information * * Date * * Copyright notice */11.3 Declaration
  30. 30. Class/interface See Documentationdocumentation standard for class /comment (/**...*/) interfacesClass or interfacestatementClass/interface This commentimplementation should contain anycomment (/*...*/), class-wide orif necessary interface-wide information that wasnt appropriate for the class/interface documentation comment.Class (static) First the publicvariables class variables, then the protected, then package level (no access modifier), and then the private.Instance variables First public, then
  31. 31. protected, then package level (no access modifier), and then private. Methods These methods should be grouped by functionality rather than by scope or accessibility. For example, a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier.11.4 IndentationFour spaces should be used as the unit ofindentation. The exact construction of theindentation (spaces vs. tabs) is unspecified.
  32. 32. Tabs must be set exactly every 8 spaces (not4).11.5 Line LengthAvoid lines longer than 80 characters, sincetheyre not handled well by many terminalsand tools.Note: Examples for use in documentationshould have a shorter line length-generallyno more than 70 characters.11.5 Wrapping LinesWhen an expression will not fit on a singleline, break it according to these generalprinciples:Break after a comma.Break before an operator.Prefer higher-level breaks to lower-levelbreaks.
  33. 33. Align the new line with the beginning of theexpression at the same level on the previousline.If the above rules lead to confusing code orto code thats squished up against the rightmargin, just indent 8 spaces instead.Here are some examples of breakingmethod calls:someMethod(longExpression1,longExpression2, longExpression3, longExpression4, longExpression5); var =someMethod1(longExpression1, someMethod2(longExpression2, longExpression3));Following are two examples of breaking anarithmetic expression. The first is preferred,since the break occurs outside theparenthesized expression, which is at ahigher level.longName1 = longName2 * (longName3 +longName4 - longName5)
  34. 34. + 4 * longname6; // PREFERlongName1 = longName2 * (longName3 +longName4 - longName5) + 4 *longname6; // AVOIDFollowing are two examples of indentingmethod declarations. The first is theconventional case. The second would shiftthe second and third lines to the far right if itused conventional indentation, so instead itindents only 8 spaces.//CONVENTIONAL INDENTATIONsomeMethod(int anArg, Object anotherArg,String yetAnotherArg, Object andStillAnother) { ...}//INDENT 8 SPACES TO AVOID VERYDEEP INDENTS
  35. 35. private static synchronizedhorkingLongMethodName(int anArg, Object anotherArg, StringyetAnotherArg, Object andStillAnother) { ...}Line wrapping for if statements shouldgenerally use the 8-space rule, sinceconventional (4 space) indentation makesseeing the body difficult. For example://DONT USE THIS INDENTATIONif ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { //BADWRAPS doSomethingAboutIt(); //MAKETHIS LINE EASY TO MISS}//USE THIS INDENTATION INSTEAD
  36. 36. if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt();}//OR USE THISif ((condition1 && condition2) || (condition3&& condition4) ||!(condition5 && condition6)) { doSomethingAboutIt();}Here are three acceptable ways to formatternary expressions:alpha = (aLongBooleanExpression) ? beta :gamma;alpha = (aLongBooleanExpression) ? beta : gamma;alpha = (aLongBooleanExpression) ? beta : gamma;
  37. 37. 11.6 DeclarationOne declaration per line is recommendedsince it encourages commenting. In otherwords,int level; // indentation levelint size; // size of tableis preferred overint level, size;Do not put different types on the same line.Example:int foo, fooarray[]; //WRONG!
  38. 38. Note: The examples above use one spacebetween the type and the identifier. Anotheracceptable alternative is to use tabs, e.g.:int level; // indentation levelint size; // size of tableObject currentEntry; // currently selectedtable entry11.7 InitializationTry to initialize local variables where theyredeclared. The only reason not to initialize avariable where its declared is if the initialvalue depends on some computationoccurring first.11.8 PlacementPut declarations only at the beginning ofblocks. (A block is any code surrounded bycurly braces "{" and "}".) Dont wait todeclare variables until their first use; it can
  39. 39. confuse the unwary programmer and hampercode portability within the scope.void myMethod() {int int1 = 0; // beginning of methodblock if (condition) { int int2 = 0; // beginning of "if" block ... }}The one exception to the rule is indexes offor loops, which in Java can be declared inthe for statement:for (int i = 0; i < maxLoops; i++) { ... }Avoid local declarations that hidedeclarations at higher levels. For example,do not declare the same variable name in aninner block:
  40. 40. int count;...myMethod() { if (condition) { int count = 0; // AVOID! ... } ...}11.9 Class and Interface DeclarationsWhen coding Java classes and interfaces, thefollowing formatting rules should befollowed:No space between a method name and theparenthesis "(" starting its parameter listOpen brace "{" appears at the end of thesame line as the declaration statementClosing brace "}" starts a line by itselfindented to match its corresponding opening
  41. 41. statement, except when it is a null statementthe "}" should appear immediately after the"{"class Sample extends Object { int ivar1; int ivar2; Sample(int i, int j) { ivar1 = i; ivar2 = j; } int emptyMethod() {} ...}A blank line separates methods11.10 StatementsSimple Statements
  42. 42. Each line should contain at most onestatement.Example:argv++; // Correctargc--; // Correctargv++; argc--; // AVOID! Compound StatementsCompound statements are statements thatcontain lists of statements enclosed in braces"{ statements }". See the following sectionsfor examples.The enclosed statements should be indentedone more level than the compoundstatement.The opening brace should be at the end ofthe line that begins the compound statement;the closing brace should begin a line and be
  43. 43. indented to the beginning of the compoundstatement.Braces are used around all statements, evensingle statements, when they are part of acontrol structure, such as a if-else or forstatement. This makes it easier to addstatements without accidentally introducingbugs due to forgetting to add braces.return StatementsA return statement with a value should notuse parentheses unless they make the returnvalue more obvious in some way.Example:return;return myDisk.size();return (size ? size : defaultSize);if, if-else, if else-if else Statements
  44. 44. The if-else class of statements should havethe following form:if (condition) { statements;}if (condition) { statements;} else { statements;}if (condition) { statements;} else if (condition) { statements;} else { statements;}Note: if statements always use braces {}.Avoid the following error-prone form:
  45. 45. if (condition) //AVOID! THIS OMITS THEBRACES {}! statement;for StatementsA for statement should have the followingform:for (initialization; condition; update) { statements;}An empty for statement (one in which all thework is done in the initialization, condition,and update clauses) should have thefollowing form:for (initialization; condition; update);When using the comma operator in theinitialization or update clause of a forstatement, avoid the complexity of using
  46. 46. more than three variables. If needed, useseparate statements before the for loop (forthe initialization clause) or at the end of theloop (for the update clause).while StatementsA while statement should have the followingform:while (condition) { statements;}An empty while statement should have thefollowing form:while (condition);do-while StatementsA do-while statement should have thefollowing form:do {
  47. 47. statements;} while (condition);switch StatementsA switch statement should have thefollowing form:switch (condition) {case ABC: statements; /* falls through */case DEF: statements; break;case XYZ: statements; break;default: statements;
  48. 48. break;}Every time a case falls through (doesntinclude a break statement), add a commentwhere the break statement would normallybe. This is shown in the preceding codeexample with the /* falls through */comment.Every switch statement should include adefault case. The break in the default case isredundant, but it prevents a fall-througherror if later another case is added.try-catch StatementsA try-catch statement should have thefollowing format:try { statements;} catch (ExceptionClass e) {
  49. 49. statements;}A try-catch statement may also be followedby finally, which executes regardless ofwhether or not the try block has completedsuccessfully.try { statements;} catch (ExceptionClass e) { statements;} finally { statements;}Blank LinesBlank lines improve readability by settingoff sections of code that are logicallyrelated.
  50. 50. Two blank lines should always be used inthe following circumstances:Between sections of a source fileBetween class and interface definitionsOne blank line should always be used in thefollowing circumstances:Between methodsBetween the local variables in a method andits first statementBefore a block or single-line commentBetween logical sections inside a method toimprove readabilityBlank SpacesBlank spaces should be used in thefollowing circumstances:A keyword followed by a parenthesis shouldbe separated by a space. Example: while (true) {
  51. 51. ... }Note that a blank space should not be usedbetween a method name and its openingparenthesis. This helps to distinguishkeywords from method calls.A blank space should appear after commasin argument lists.All binary operators except . should beseparated from their operands by spaces.Blank spaces should never separate unaryoperators such as unary minus, increment("++"), and decrement ("--") from theiroperands.Example: a += c + d; a = (a + b) / (c * d); while (d++ = s++) { n++;
  52. 52. } printSize("size is " + foo + "n");The expressions in a for statement should beseparated by blank spaces. Example: for (expr1; expr2; expr3)Casts should be followed by a blank space.Examples: myMethod((byte) aNum, (Object) x); myMethod((int) (cp + 5), ((int) (i + 3)) + 1);Naming Conventions Summary Identifier Rules for Examples Type Naming Packages The prefix of com.sun.eng a unique com.apple.quicktime.v2 package edu.cmu.cs.bovik.cheese name is always
  53. 53. written in all-lowercaseASCII lettersand should beone of thetop-leveldomainnames,currentlycom, edu,gov, mil, net,org, or one ofthe Englishtwo-lettercodesidentifyingcountries asspecified inISO Standard3166, 1981.Subsequentcomponentsof the
  54. 54. package name vary according to an organizations own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names.Classes Class names class Raster; should be class ImageSprite;
  55. 55. nouns, inmixed casewith the firstletter of eachinternal wordcapitalized.Try to keepyour classnames simpleanddescriptive.Use wholewords-avoidacronymsandabbreviations(unless theabbreviationis much morewidely usedthan the longform, such asURL or
  56. 56. HTML).Interfaces Interface interface names should RasterDelegate; be capitalized interface Storing; like class names.Methods Methods run(); should be runFast(); verbs, in getBackground(); mixed case with the first letter lowercase, with the first letter of each internal word capitalized.Variables Except for int i; variables, all char c; instance, float myWidth;
  57. 57. class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though 2 both are allowed. Variable names should2 Java Coding Standards
  58. 58. be short yetmeaningful.The choice ofa variablename shouldbemnemonic-that is,designed toindicate tothe casualobserver theintent of itsuse. One-charactervariablenames shouldbe avoidedexcept fortemporary"throwaway"variables.Common
  59. 59. names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.Constant The names of static final ints variables MIN_WIDTH = 4; declared static final int class MAX_WIDTH = 999; constants and static final int of ANSI GET_THE_CPU = 1; constants should be all uppercase with words separated by underscores ("_"). (ANSI constants
  60. 60. should be avoided, for ease of debugging.)References:www.java.sun.com