This document serves as the complete definition of Google’s coding standards for source code in the Java™ Programming Language. A Java source file is described as being in Google Style if and only if it adheres to the rules herein.
Like other programming style guides, the issues covered span not only aesthetic issues of formatting, but other types of conventions or coding standards as well. However, this document focuses primarily on the hard-and-fast rules that we follow universally, and avoids giving advice that isn’t clearly enforceable (whether by human or tool).
1.1 Terminology notes
In this document, unless otherwise clarified:
Other «terminology notes» will appear occasionally throughout the document.
1.2 Guide notes
Example code in this document is non-normative. That is, while the examples are in Google Style, they may not illustrate the only stylish way to represent the code. Optional formatting choices made in examples should not be enforced as rules.
2 Source file basics
2.1 File name
2.2 File encoding: UTF-8
Source files are encoded in UTF-8.
2.3 Special characters
2.3.1 Whitespace characters
Aside from the line terminator sequence, the ASCII horizontal space character (0x20) is the only whitespace character that appears anywhere in a source file. This implies that:
2.3.2 Special escape sequences
2.3.3 Non-ASCII characters
For the remaining non-ASCII characters, either the actual Unicode character (e.g. β ) or the equivalent Unicode escape (e.g. \u221e ) is used. The choice depends only on which makes the code easier to read and understand, although Unicode escapes outside string literals and comments are strongly discouraged.
Tip: In the Unicode escape case, and occasionally even when actual Unicode characters are used, an explanatory comment can be very helpful.
Example
Discussion
String unitAbbrev = «ΞΌs»;
Best: perfectly clear even without a comment.
String unitAbbrev = «\u03bcs»; // «ΞΌs»
Allowed, but there’s no reason to do this.
String unitAbbrev = «\u03bcs»; // Greek letter mu, «s»
Allowed, but awkward and prone to mistakes.
String unitAbbrev = «\u03bcs»;
Poor: the reader has no idea what this is.
return ‘\ufeff’ + content; // byte order mark
Good: use escapes for non-printable characters, and comment if necessary.
Tip: Never make your code less readable simply out of fear that some programs might not handle non-ASCII characters properly. If that should happen, those programs are broken and they must be fixed.
3 Source file structure
A source file consists of, in order:
Exactly one blank line separates each section that is present.
3.1 License or copyright information, if present
If license or copyright information belongs in a file, it belongs here.
3.2 Package statement
The package statement is not line-wrapped. The column limit (Section 4.4, Column limit: 100) does not apply to package statements.
3.3 Import statements
3.3.1 No wildcard imports
Wildcard imports, static or otherwise, are not used.
3.3.2 No line-wrapping
Import statements are not line-wrapped. The column limit (Section 4.4, Column limit: 100) does not apply to import statements.
3.3.3 Ordering and spacing
Imports are ordered as follows:
If there are both static and non-static imports, a single blank line separates the two blocks. There are no other blank lines between import statements.
Within each block the imported names appear in ASCII sort order. (Note: this is not the same as the import statements being in ASCII sort order, since ‘.’ sorts before ‘;’.)
3.3.4 No static import for classes
Static import is not used for static nested classes. They are imported with normal imports.
3.4 Class declaration
3.4.1 Exactly one top-level class declaration
Each top-level class resides in a source file of its own.
3.4.2 Ordering of class contents
The order you choose for the members and initializers of your class can have a great effect on learnability. However, there’s no single correct recipe for how to do it; different classes may order their contents in different ways.
What is important is that each class uses some logical order, which its maintainer could explain if asked. For example, new methods are not just habitually added to the end of the class, as that would yield «chronological by date added» ordering, which is not a logical ordering.
3.4.2.1 Overloads: never split
Methods of a class that share the same name appear in a single contiguous group with no other members in between. The same applies to multiple constructors (which always have the same name). This rule applies even when modifiers such as static or private differ between the methods.
4 Formatting
Terminology Note:block-like construct refers to the body of a class, method or constructor. Note that, by Section 4.8.3.1 on array initializers, any array initializer may optionally be treated as if it were a block-like construct.
4.1 Braces
4.1.1 Use of optional braces
Other optional braces, such as those in a lambda expression, remain optional.
4.1.2 Nonempty blocks: K & R style
Braces follow the Kernighan and Ritchie style («Egyptian brackets») for nonempty blocks and block-like constructs:
Exception: In places where these rules allow a single statement ending with a semicolon ( ; ), a block of statements can appear, and the opening brace of this block is preceded by a line break. Blocks like these are typically introduced to limit the scope of local variables, for example inside switch statements.
A few exceptions for enum classes are given in Section 4.8.1, Enum classes.
4.1.3 Empty blocks: may be concise
An empty block or block-like construct may be in K & R style (as described in Section 4.1.2). Alternatively, it may be closed immediately after it is opened, with no characters or line break in between ( <> ), unless it is part of a multi-block statement (one that directly contains multiple blocks: if/else or try/catch/finally ).
4.2 Block indentation: +2 spaces
Each time a new block or block-like construct is opened, the indent increases by two spaces. When the block ends, the indent returns to the previous indent level. The indent level applies to both code and comments throughout the block. (See the example in Section 4.1.2, Nonempty blocks: K & R Style.)
4.3 One statement per line
Each statement is followed by a line break.
4.4 Column limit: 100
Java code has a column limit of 100 characters. A «character» means any Unicode code point. Except as noted below, any line that would exceed this limit must be line-wrapped, as explained in Section 4.5, Line-wrapping.
Each Unicode code point counts as one character, even if its display width is greater or less. For example, if using fullwidth characters, you may choose to wrap the line earlier than where this rule strictly requires.
Exceptions:
4.5 Line-wrapping
Terminology Note: When code that might otherwise legally occupy a single line is divided into multiple lines, this activity is called line-wrapping.
There is no comprehensive, deterministic formula showing exactly how to line-wrap in every situation. Very often there are several valid ways to line-wrap the same piece of code.
Note: While the typical reason for line-wrapping is to avoid overflowing the column limit, even code that would in fact fit within the column limit may be line-wrapped at the author’s discretion.
Tip: Extracting a method or local variable may solve the problem without the need to line-wrap.
4.5.1 Where to break
The prime directive of line-wrapping is: prefer to break at a higher syntactic level. Also:
Note: The primary goal for line wrapping is to have clear code, not necessarily code that fits in the smallest number of lines.
4.5.2 Indent continuation lines at least +4 spaces
When line-wrapping, each line after the first (each continuation line) is indented at least +4 from the original line.
When there are multiple continuation lines, indentation may be varied beyond +4 as desired. In general, two continuation lines use the same indentation level if and only if they begin with syntactically parallel elements.
Section 4.6.3 on Horizontal alignment addresses the discouraged practice of using a variable number of spaces to align certain tokens with previous lines.
4.6 Whitespace
4.6.1 Vertical Whitespace
A single blank line always appears:
A single blank line may also appear anywhere it improves readability, for example between statements to organize the code into logical subsections. A blank line before the first member or initializer, or after the last member or initializer of the class, is neither encouraged nor discouraged.
Multiple consecutive blank lines are permitted, but never required (or encouraged).
4.6.2 Horizontal whitespace
Beyond where required by the language or other style rules, and apart from literals, comments and Javadoc, a single ASCII space also appears in the following places only.
This rule is never interpreted as requiring or forbidding additional space at the start or end of a line; it addresses only interior space.
4.6.3 Horizontal alignment: never required
Terminology Note:Horizontal alignment is the practice of adding a variable number of additional spaces in your code with the goal of making certain tokens appear directly below certain other tokens on previous lines.
This practice is permitted, but is never required by Google Style. It is not even required to maintain horizontal alignment in places where it was already used.
Here is an example without alignment, then using alignment:
Tip: Alignment can aid readability, but it creates problems for future maintenance. Consider a future change that needs to touch just one line. This change may leave the formerly-pleasing formatting mangled, and that is allowed. More often it prompts the coder (perhaps you) to adjust whitespace on nearby lines as well, possibly triggering a cascading series of reformattings. That one-line change now has a «blast radius.» This can at worst result in pointless busywork, but at best it still corrupts version history information, slows down reviewers and exacerbates merge conflicts.
4.7 Grouping parentheses: recommended
Optional grouping parentheses are omitted only when author and reviewer agree that there is no reasonable chance the code will be misinterpreted without them, nor would they have made the code easier to read. It is not reasonable to assume that every reader has the entire Java operator precedence table memorized.
4.8 Specific constructs
4.8.1 Enum classes
After each comma that follows an enum constant, a line break is optional. Additional blank lines (usually just one) are also allowed. This is one possibility:
An enum class with no methods and no documentation on its constants may optionally be formatted as if it were an array initializer (see Section 4.8.3.1 on array initializers).
Since enum classes are classes, all other rules for formatting classes apply.
4.8.2 Variable declarations
4.8.2.1 One variable per declaration
Every variable declaration (field or local) declares only one variable: declarations such as int a, b; are not used.
Exception: Multiple variable declarations are acceptable in the header of a for loop.
4.8.2.2 Declared when needed
Local variables are not habitually declared at the start of their containing block or block-like construct. Instead, local variables are declared close to the point they are first used (within reason), to minimize their scope. Local variable declarations typically have initializers, or are initialized immediately after declaration.
4.8.3 Arrays
4.8.3.1 Array initializers: can be «block-like»
Any array initializer may optionally be formatted as if it were a «block-like construct.» For example, the following are all valid (not an exhaustive list):
4.8.3.2 No C-style array declarations
4.8.4 Switch statements
Terminology Note: Inside the braces of a switch block are one or more statement groups. Each statement group consists of one or more switch labels (either case FOO: or default: ), followed by one or more statements (or, for the last statement group, zero or more statements).
4.8.4.1 Indentation
As with any other block, the contents of a switch block are indented +2.
After a switch label, there is a line break, and the indentation level is increased +2, exactly as if a block were being opened. The following switch label returns to the previous indentation level, as if a block had been closed.
4.8.4.2 Fall-through: commented
4.8.4.3 Presence of the default label
Each switch statement includes a default statement group, even if it contains no code.
Exception: A switch statement for an enum type may omit the default statement group, if it includes explicit cases covering all possible values of that type. This enables IDEs or other static analysis tools to issue a warning if any cases were missed.
4.8.5 Annotations
4.8.5.1 Type-use annotations
4.8.5.2 Class annotations
Annotations applying to a class appear immediately after the documentation block, and each annotation is listed on a line of its own (that is, one annotation per line). These line breaks do not constitute line-wrapping (Section 4.5, Line-wrapping), so the indentation level is not increased. Example:
4.8.5.3 Method and constructor annotations
The rules for annotations on method and constructor declarations are the same as the previous section. Example:
Exception: A single parameterless annotation may instead appear together with the first line of the signature, for example:
4.8.5.4 Field annotations
Annotations applying to a field also appear immediately after the documentation block, but in this case, multiple annotations (possibly parameterized) may be listed on the same line; for example:
4.8.5.5 Parameter and local variable annotations
There are no specific rules for formatting annotations on parameters or local variables (except, of course, when the annotation is a type-use annotation).
4.8.6 Comments
This section addresses implementation comments. Javadoc is addressed separately in Section 7, Javadoc.
Any line break may be preceded by arbitrary whitespace followed by an implementation comment. Such a comment renders the line non-blank.
4.8.6.1 Block comment style
Comments are not enclosed in boxes drawn with asterisks or other characters.
4.8.7 Modifiers
Class and member modifiers, when present, appear in the order recommended by the Java Language Specification:
4.8.8 Numeric Literals
5 Naming
5.1 Rules common to all identifiers
5.2 Rules by identifier type
5.2.1 Package names
5.2.2 Class names
Class names are written in UpperCamelCase.
There are no specific rules or even well-established conventions for naming annotation types.
5.2.3 Method names
Method names are written in lowerCamelCase.
5.2.4 Constant names
Constant names use UPPER_SNAKE_CASE : all uppercase letters, with each word separated from the next by a single underscore. But what is a constant, exactly?
These names are typically nouns or noun phrases.
5.2.5 Non-constant field names
Non-constant field names (static or otherwise) are written in lowerCamelCase.
5.2.6 Parameter names
Parameter names are written in lowerCamelCase.
One-character parameter names in public methods should be avoided.
5.2.7 Local variable names
Local variable names are written in lowerCamelCase.
Even when final and immutable, local variables are not considered to be constants, and should not be styled as constants.
5.2.8 Type variable names
Each type variable is named in one of two styles:
5.3 Camel case: defined
Sometimes there is more than one reasonable way to convert an English phrase into camel case, such as when acronyms or unusual constructs like «IPv6» or «iOS» are present. To improve predictability, Google Style specifies the following (nearly) deterministic scheme.
Beginning with the prose form of the name:
Note that the casing of the original words is almost entirely disregarded. Examples:
Prose form
Correct
Incorrect
«XML HTTP request»
XmlHttpRequest
XMLHTTPRequest
«new customer ID»
newCustomerId
newCustomerID
«inner stopwatch»
innerStopwatch
innerStopWatch
«supports IPv6 on iOS?»
supportsIpv6OnIos
supportsIPv6OnIOS
«YouTube importer»
YouTubeImporter YoutubeImporter *
*Acceptable, but not recommended.
Note: Some words are ambiguously hyphenated in the English language: for example «nonempty» and «non-empty» are both correct, so the method names checkNonempty and checkNonEmpty are likewise both correct.
6 Programming Practices
6.1 @Override : always used
A method is marked with the @Override annotation whenever it is legal. This includes a class method overriding a superclass method, a class method implementing an interface method, and an interface method respecifying a superinterface method.
6.2 Caught exceptions: not ignored
When it truly is appropriate to take no action whatsoever in a catch block, the reason this is justified is explained in a comment.
6.3 Static members: qualified using class
When a reference to a static class member must be qualified, it is qualified with that class’s name, not with a reference or expression of that class’s type.
6.4 Finalizers: not used
Tip: Don’t do it. If you absolutely must, first read and understand Effective Java Item 8, «Avoid finalizers and cleaners» very carefully, and then don’t do it.
7 Javadoc
7.1 Formatting
7.1.1 General form
The basic formatting of Javadoc blocks is as seen in this example:
. or in this single-line example:
7.1.2 Paragraphs
One blank lineβthat is, a line containing only the aligned leading asterisk ( * )βappears between paragraphs, and before the group of block tags if present. Each paragraph except the first has
immediately before the first word, with no space after it. HTML tags for other block-level elements, such as
or
, are not preceded with
7.1.3 Block tags
7.2 The summary fragment
Each Javadoc block begins with a brief summary fragment. This fragment is very important: it is the only part of the text that appears in certain contexts such as class and method indexes.
7.3 Where Javadoc is used
At the minimum, Javadoc is present for every public class, and every public or protected member of such a class, with a few exceptions noted below.
Additional Javadoc content may also be present, as explained in Section 7.3.4, Non-required Javadoc.
7.3.1 Exception: self-explanatory members
7.3.2 Exception: overrides
Javadoc is not always present on a method that overrides a supertype method.
7.3.4 Non-required Javadoc
Other classes and members have Javadoc as needed or desired.
Whenever an implementation comment would be used to define the overall purpose or behavior of a class or member, that comment is written as Javadoc instead (using /** ).
Non-required Javadoc is not strictly required to follow the formatting rules of Sections 7.1.1, 7.1.2, 7.1.3, and 7.2, though it is of course recommended.
Code conventions are important to programmers for a number of reasons:
80% of the lifetime cost of a piece of software goes to maintenance.
Hardly any software is maintained for its whole life by the original author.
Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.
If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create.
Static Code Analysis
Setting up Checkstyle
Checkstyle will help educate and enforce our coding standards. You can set up your IDE to use Checkstyle to examine code for conformance to the standards. Learn more about the checks or Google the error message to find out why it complains about certain things.
Install the CheckStyle-IDEA plugin. File | Preferences | Plugins | Browse Repositories. If nothing shows up in the list you may need to set the Http Proxy Settings. I had to set mine to manual: http://us-auto.proxy.lexmark.com:8080. Search for CheckStyle-IDEA and install it.
Set the configuration file. In File | Preferences you will now have CheckStyle settings. Click plus sign to add the configuration file. Set the configuration file to http://lexmarkweb.github.io/coding-standards/java-checks-6.1.1.xml (for IntelliJ 13)
Make this the active configuration.
Check your code. With you code open in IntelliJ right click and you will see «Check Current File».
A file consists of sections that should be separated by blank lines and an optional comment identifying each section.
Source files are encoded in UTF-8
Files longer than 2000 lines are cumbersome and should be avoided.
Each Java source file contains a single public class or interface. When private classes and interfaces are associated with a public class, you can put them in the same source file as the public class. The public class should be the first class or interface in the file.
Java source files have the following ordering:
All source files should begin with a c-style comment that lists the programmer(s), the date, a copyright notice, and also a brief description of the purpose of the program.
The first non-comment line of most Java source files is a package statement. After that, import statements can follow.
Import statements must be grouped with associated packages together and one blank line between groups
Imported classes should always be listed explicitly
Four spaces should be used as the unit of indentation. The exact construction of the indentation is 4 spaces.
Special characters like TAB and page break should be avoided
Avoid lines longer than 120 characters, since theyβre not handled well by many terminals and tools.
When an expression will not fit on a single line, break it according to these general principles:
β’ Break after a comma.
β’ Break before an operator.
β’ For arithmetic expressions, avoid breaking within a set of parentheses.
β’ Align the new line with the beginning of the expression at the same level on the previous line.
β’ If the above rules lead to confusing code or to code thatβs squished up against the right margin, just indent 8 spaces instead.
Here are some examples of breaking method calls:
Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.
Following 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 8 spaces.
Here are three acceptable ways to format ternary expressions:
Java programs can have two kinds of comments: implementation comments and documentation comments. Implementation comments are those found in C++, which are delimited by /. /, and //. Documentation comments (known as «doc comments») are
Implementation comments are meant for commenting out code or for comments about the particular implementation. Doc comments are meant to describe the specification of the code, from an implementation-free perspective to be read by developers who might not necessarily have the source code at hand.
Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. For example, information about how the corresponding package is built or in what directory it resides should not be included as a comment.
Avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves.
Note: The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer.
Comments should not be enclosed in large boxes drawn with asterisks or other characters.
Comments should never include special characters such as form-feed and backspace.
Implementation Comment Formats
Programs can have four styles of implementation comments: block, single-line, trailing and end-of-line.
Block comments are used to provide descriptions of files, methods, data structures and algorithms.
Block comments should be used at the beginning of each file and before each method. They can also be used in other places, such as within methods.
Block comments inside a function or method should be indented to the same level as the code they describe.
A block comment should be preceded by a blank line to set it apart from the rest of the code.
Block comments have an asterisk » * » at the beginning of each line except the first.
Short comments can appear on a single line indented to the level of the code that follows. If a comment can’t be written in a single line, it should follow the block comment format. A single-line comment should be preceded by a blank line. Here’s an example of a single-line comment in Java code
Notice that top-level classes and interfaces are not indented, while their members are. The first line of doc comment ( /** ) for classes and interfaces is not indented; subsequent doc comment lines each have 1 space of indentation (to vertically align the asterisks). Members, including constructors, have 4 spaces for the first doc comment line and 5 spaces thereafter.
If you need to give information about a class, interface, variable, or method that isn’t appropriate for documentation, use an implementation block comment or single-line comment immediately after the declaration. For example, details about the implementation of a class should go in in such an implementation block comment following the class statement, not in the class doc comment.
Doc comments should not be positioned inside a method or constructor definition block, because Java associates documentation comments with the first declaration after the comment.
All classes are to include a comment block that describing the basic purpose of the class. (This is also a good place to put any overarching TODO statements).
All public methods need to include Java doc comments except for accessors.
Parameters are to be included, but do not require documentation unless it is something meaningful i.e. avoid * @param name The name
Return statements are to be included and documented.
Thrown exceptions may be included, but do not need to be documented.
Protected / Private methods should include java doc comments when they are not easily understood. This is up to developer / reviewer discretion.
One declaration per line. In other words,
Try to initialize local variables where they’re declared. The only reason not to initialize a variable where it’s declared is if the initial value depends on some computation occurring first.
Local variables are not habitually declared at the start of their containing block or block-like construct. Instead, local variables are declared close to the point they are first used (within reason), to minimize their scope. Local variable declarations typically have initializers, or are initialized immediately after declaration.
Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:
Class and Interface Declarations
When coding Java classes and interfaces, the following formatting rules should be followed:
No space between a method name and the parenthesis «(» starting its parameter list
Closing brace «>» starts a line by itself indented to match its corresponding opening statement, except when it is a null statement the «>» should appear immediately after the «<"
Methods are separated by a blank line
Annotations applying to a class, method or constructor appear immediately after the documentation block, and each annotation is listed on a line of its own (that is, one annotation per line). These line breaks do not constitute line-wrapping so the indentation level is not increased
Each line should contain at most one statement. Example:
Compound statements are statements that contain lists of statements enclosed in braces «< statements >«. 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 statement; the closing brace should begin a line and be indented to the beginning of the compound statement.
Braces are used around all statements, even single statements, when they are part of a control structure, such as an if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.
A return statement with a value should not use parentheses unless they make the return value more obvious in some way. Example:
if, if-else, if else-if else Statements
The if-else class of statements should have the following form:
Note: if statements always use braces, <>. Avoid the following error-prone form:
A for statement should have the following form:
An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form:
When using the comma operator in the initialization or update clause of a for statement, avoid the complexity of using more than three variables. If needed, use separate statements before the for loop (for the initialization clause) or at the end of the loop (for the update clause).
A while statement should have the following form:
An empty while statement should have the following form:
A do-while statement should have the following form:
A switch statement should have the following form:
Every time a case falls through (doesn’t include a break statement), add a comment where the break 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 break in the default case is redundant, but it prevents a fall-through error if later another case is added.
A try-catch statement should have the following format:
A try-catch statement may also be followed by finally, which executes regardless of whether or not the try block has completed successfully.
for collection loop
A for collection loop should have following format
Blank lines improve readability by setting off sections of code that are logically related.
Two blank lines should always be used in the following circumstances:
Between sections of a source file
Between class and interface definitions
One blank line should always be used in the following circumstances:
Between the local variables in a method and its first statement
Before a block or single-line comment
Between logical sections inside a method to improve readability
Blank spaces should be used in the following circumstances:
Note that a blank space should not be used between a method name and its opening parenthesis. This helps to distinguish keywords from method calls.
A blank space should appear after commas in argument lists.
Naming conventions make programs more understandable by making them easier to read. They can also give information about the function of the identifier-for example, whether it’s a constant, package, or class-which can be helpful in understanding the code.
Identifier Type
Rules of Naming
Examples
Packages
The prefix of a unique package name is always written in all-lowercase ASCII 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 countries as specified in ISO Standard 3166, 1981.
Subsequent components of the package name vary according to an organization’s own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names.
Classes
Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).
Implementation class should have suffix Impl
class Raster; class ImageSprite;
Interfaces
Interface names should be capitalized like class names.
interface RasterDelegate; interface Storing;
Methods
Methods should be verbs, in Camel Case
The term compute can be used where something is computed
The term find can be used when we look up something
Is prefix is used for Boolean getter and setters
Acronyms such as XML and HTTP should be treated as words, such as getHttp(), getXml(). Not getXML() or getHTTP()
Variable names should be meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for loop control variables.
Common names for temporary variables are i, j, k, m, and n.
Boolean variable names should not be negative, for instance, isNotLoaded, unAttached.
int i; char c; float myWidth;
Constants
The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores («`_`»).
«` static final int MIN_WIDTH = 4; static final int MAX_WIDTH = 999; static final int GET_THE_CPU = 1; «`
Type conversions must always be done explicitly never rely on implicit type conversion
Array specifiers must be attached to the type not the variable
Providing Access to Instance and Class Variables
Don’t make any instance or class variable public without good reason. Just because itβs a class level variable doesnβt mean it needs a getter and setter.
One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior
Referring to Class Variables and Methods
Avoid using an object to access a class (static) variable or method. Use a class name instead. For example:
String constants should be used except for «» or null, some exceptions would be logging and errors.
should be written as
It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems. Even if the operator precedence seems clear to you, it might not be to others-you shouldn’t assume that other programmers know precedence as well as you do.
Try to make the structure of your program match the intent. Example:
should instead be written as
! operator and conditional expressions
@Override: always used
A method is marked with the @Override annotation whenever it is legal. This includes a class method overriding a superclass method, a class method implementing an interface method, and an interface method respecifying a superinterface method.
Exception:@Override may be omitted when the parent method is @Deprecated.
Caught exceptions: not ignored
Except as noted below, it is very rarely correct to do nothing in response to a caught exception. Exceptions should usually be at least logged at debug or trace level.
When it truly is appropriate to take no action whatsoever in a catch block, the reason this is justified is explained in a comment.
Exception: In tests, a caught exception may be ignored without comment if it is named expected. The following is a very common idiom for ensuring that the method under test does throw an exception of the expected type, so a comment is unnecessary here.
Each project/application should choose and enforce usage of a standard logging library (ex. Log4j)
Each project/application should document when each logging level should be used
All exceptions should at least be logged (excluding «expected» exceptions like some parsing exceptions)
Exceptions should be chained except for good reasons
When adding temporary logging for trouble shooting, add a // TODO remove temporary logs comment by set of log messages that should be removed.
Consult these resources for guidance on secure coding practices, particularly CERT standard. Some stylistic considerations are mentioned further on.
Exercise extreme caution with switch statements, especially fall-through statements. If you must use fall-through, please re-think your design approach. If, after much consideration, you still need fall-through, be judicious and deliberate to mark ALL fall-through points with a comment as indicated earlier in this guide.
Security checks should be located and maintained in a single place. Be sure to apply «Donβt Repeat Yourself» (DRY) principal frequently and comprehensively to all security check logic throughout the application.
When to Use Generics
With Collections. The Java Collections framework is excellent and should be used instead of Arrays.
If you find yourself doing a lot (or perhaps even a little) casting of types you might want to consider Generics
If you are using variables of type Object to store values form various classes, you might want to use Generics instead.
Naming Convention for Generic types in a class definition
Oracle recommends the following naming convention:
For a version more suitable for printing, use this PDF File.
This document comprises an opinionated set of conventions for the Java TM programming language. It is intended for use by software engineering teams to employ a common style when writing Java code.
The following is the original copyright notice provided by Sun. It is to be honored, particularly by adhering to proper attribution as well as usage and redistribution restrictions stated below.
Though redistribution of this document is discouraged, citing the warning above, you may copy, adapt, and redistribute this document for non-commercial use or for your own internal use in a commercial setting. However, you may not republish this document, nor may you publish or distribute any adaptation of this document for other than non-commercial use or your own internal use, without first obtaining express written approval from Oracle.
When copying, adapting, or redistributing this document in keeping with the guidelines above, you are required to provide proper attribution to Sun. If you reproduce or distribute the document without making any substantive modifications to its content, please use the following attribution line:
Copyright 1995-1999 Sun Microsystems, Inc. All rights reserved. Used by permission.
If you modify the document content in a way that alters its meaning, for example, to conform with your own company’s coding conventions, please use this attribution line:
Adapted with permission from CODE CONVENTIONS FOR THE JAVA TM PROGRAMMING LANGUAGE. Copyright 1995-1999 Sun Microsysytems[sic], Inc. All rights reserved.
Either way, please include a hypertext link or other reference to the Java Code Conventions Web site at http://www.oracle.com/technetwork/java/codeconvtoc-136057.html
Code conventions are important to programmers for a number of reasons:
This section lists commonly used file suffixes and names.
The following table lists the file suffixes used by Java software.
Suffix
File Type
.java
Java source
.class
Java bytecode
.jar
Java archive
The following table lists frequently used file names. These files are not required for every directory; however, when they exist the specified names should be used.
File Name
Use
Makefile
Preferred name for makefiles.
README
Preferred name for the file that summarizes the contents of a particular directory.
A file consists of sections that should be separated by blank lines and, optionally, a comment identifying each section. Files longer than 2000 lines are cumbersome and should be avoided. Refer to Appendix A for an example of a complete Java program properly formatted.
Each Java source file should contain at most one public class or interface. When private classes and interfaces are associated with a public class, put them in the same source file as the public class. The public class should be the first class or interface in the file.
Java source files have the following ordering.
All source files should begin with a C-style block comment ( /*. */ ) that lists the file name, RCS keywords, copyright notice, among other things. Section 5.1.1 gives additional information on block comments; however, all other block comments besides the header comments use the // delimeter.
The following gives a simple example of header comments.
The use of the XML tags in the header comments are provided as a suggestion. They allow scripts to be run across the source tree to globally modify the values of things like the RCS keywords or copyright notice in individual files when needed.
The first non-comment line of a Java source files should be the package statement. After that, import statements can follow. Place a single blank line between the header comments and the package statement. Also place a single blank line between the package statement and the first import statement.
The following gives a simple example of package and import statements.
The following are additional conventions; the general Java conventions make no reference to them.
The use of * in an import statement (e.g., import java.awt.* ) should not be used, even though Java provides the functionality. It is considered poor programming style and can lead to ambiguities when multiple classes are used with the same name but from different packages.
Do not import anything from java.lang directly. These statements are redundant as the complete package is always imported by the compiler and run-time environment regardless.
Do not import any classes which are not used directly.
The following gives an example of proper ordering of import statements.
The following section varies dramatically from the original Java conventions. What is presented here is much more rigid and structured.
A class declaration should adhere to the following structure (in order).
The following gives an example of the basic structure of a class declaration.
An interface declaration is very similar in structure to that of a class. The major differences are the following.
The following gives an example of the basic structure of an interface declaration.
The unit of indentation should be 4 spaces. Tab-stops should be set exactly every 8 spaces.
All indentation must be achieved via the space character; tab characters must not exist in the resultant source file.
For Emacs users, the following elisp code will automatically convert any tabs into spaces when a java file is saved.
When an expression will not fit on a single line, break it according to these general principles:
The following are two examples of breaking method calls.
The following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.
The following are two examples of indenting method declarations. The first is the conventional case. The second would shift the second and third lines too far to the right if it used conventional indentation, so instead it indents only one tab-stop.
The following are two examples to format class declarations.
The following is an example of handling a long assignment statements. Break before the equals sign and indent one tab-stop from the start of the previous line.
The following are three acceptable ways to format ternary expressions. Refer to Section 10.6.7 for appropriate use of this expression.
Implementation comments are for notes about a particular implementation or a means for temporarily removing code. Documentation comments are meant to describe the specification of the code, from an implementation-free perspective, to be read by developers who might not necessarily have the source code at hand.
In general, comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. For example, information about how the corresponding package is built or in what directory it resides should not be included as a comment.
Discussion of nontrivial or nonobvious design decisions is appropriate, but avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves. In addition, the frequency of comments sometimes reflects poor quality of code. When feeling compelled to add a comment, one should consider rewriting the code to make it clearer.
All comments should have a single blank space between the comment delimeter and the text of the comment. In addition, comments should not be enclosed in large boxes drawn with asterisks or other characters. Comments should never include special characters such as form-feed and backspace.
Programs can have four styles of implementation comments: block, single-line, trailing, and for temporarily removing code.
Block comments are used to provide descriptions of files, methods, data structures, and algorithms. Block comments may be used at the beginning of each file and before each method. They can also be used in other places, such as within methods. Block comments inside a function or method should be indented to the same level as the code they describe. A block comment should be preceded by a blank line unless it comes immediately after the start of a compound statement (Section 7.2).
The following is a simple example of a block comment.
For information about another form of block comments used for documentation, see Section 5.2.
Short comments can appear on a single line indented to the level of the code that follows. If a comment can not be written in a single line, it should follow the block comment format (Section 5.1.1). A single-line comment should be preceded by a blank line unless it comes immediately after the start of a compound statement (Section 7.2).
The following are a few examples of single-line comments.
Very short comments can appear on the same line as the code they describe but should be shifted far enough to separate them from the statements. If more than one short comment appears in a section of related code, they should all be indented to the same tab setting.
The following are a few examples of trailing comments.
Trailing comments are also used to help clarify the closing brace of a compound statement (Section 7.2). One example of this usage is at the end of a class declaration; the class name is placed in a trailing comment adjacent to the closing brace (Section 6.5). Another example occurs when several long compound statements are nested; a trailing comment can be added adjacent to the closing brace of a compound statement to help clarify which block the brace closes.
The following gives an an example for both cases of clarifying a closing brace by use of a trailing comment.
The // delimiter can comment out a partial or complete line. It can also be used in consecutive multiple lines for commenting-out entire sections of code. It is important to note that this should only be used as a temporary measure while the code is in active development; the unused code should eventually be purged as it can make the source more difficult to maintain.
The following are examples of temporarily removing code with comments.
The following is a simple example of a documentation comment used for describing a class.
Notice that top-level classes and interfaces are not indented, while their members are. The first line of documentation comment ( /** ) for classes and interfaces is not indented; subsequent documentation comment lines each have 1 space of indentation (to vertically align the asterisks). Members, including constructors, have 4 spaces for the first documentation comment line and 5 spaces thereafter. Single line documentation comments are only acceptable when describing fields.
If one needs to give information about a class, interface, method, or field that is not intended for documentation, use an appropriate implementation comment (Section 5.1) immediately after the declaration.
Java associates documentation comments with the first declaration after the comment. As a result, documentation comments should not be positioned inside a method or constructor definition block.
The following is a simple example showing the proper use of documentation comments and implementation comments.
Only one declaration per line is allowed. Even though Java permits multiple declarations on a line, it makes initialization impossible (see Section 6.2) and leads to confusion when scalars and arrays are declared on the same line. The standard Java convention is to recommend rather than require one declaration per line.
The following are examples of correct and incorrect declarations.
The previous example uses a single space between the type and the identifier. Another acceptable alternative is to use tabs.
The following is an example of declarations using tabs to separate the type from the variable.
All variables (local and class) should be initialized where they are declared.
Put all local variable declarations at the beginning of method definitions. The standard Java convention allows for declarations to appear at the beginning of any compound statement; however, this is discouraged because it can lead to issues where a variable declared at a higher scope is unwittingly hidden by one in a lower scope.
The following is an example of proper placement of declarations at the beginning of a method.
The one exception to the placement rule is indexes of for loops which in Java can be declared in the for statement.
The following is an example of a declaration of an index within the for loop.
Though Java allows modifiers in any order, a consistent ordering improves readability of code. The following is the proper order of modifiers for declarations.
When coding Java classes and interfaces, the following formatting rules should be followed.
The following is a simple example of a proper formatting of a class declaration.
Each line should contain no more than one statement.
The following is an example of correct and incorrect formatting of simple statements.
Compound statements are statements that contain lists of statements enclosed in braces ( <> ). See the following subsections for specific examples.
A return statement with a value should not use parentheses unless they make the value being returned more obvious in some way.
The following are several examples of proper use of return statements.
The if-else class of statements should have the following form.
Like all other compound statements, if statements always use braces ( <> ). As a result, do not use the following error-prone form.
A for statement should have the following form.
When using the comma operator in the initialization or update clause of a for statement, avoid the complexity of using more than three variables. If needed, use separate statements before the for loop (for the initialization clause) or at the end of the loop (for the update clause).
A while statement should have the following form.
A do-while statement should have the following form.
A switch statement should have the following form.
The first statement for each case should appear on the line following the case and should be indented one extra level.
Every time a case falls through (i.e., does not include a break statement), add a comment where the break statement would normally be. This is shown in the preceding code example with the // XXX falls through comment. Refer to Section 10.6.8 for more information on the appropriate use of the // XXX special comment.
Every switch statement should include a default case, and it should always be the last case. The break in the default case is redundant because it is the last one in the statement; however, it prevents a fall-through error if later another case is inadvertently added to the end.
A try-catch statement should have the following form.
The following is a simple example of a properly formatted try-catch-finally statement.
Blank lines improve readability by setting off sections of code that are logically related. A single blank line should always be used in the following circumstances.
Blank spaces should be used in the following circumstances.
The following is an example of proper use of blank space following a keyword.
On the other hand, a blank space should not be used between a method name and its opening parenthesis. This helps to distinguish keywords from method calls. Blank space should not appear after the the opening parenthesis or just prior to the closing parenthesis.
The following is an example of the proper use of blank space for binary operators.
The following is an example of proper use of blank spaces in a for statement.
The following are a few examples of proper use of blank space with casts.
The following are a few examples of correct package names.
Class and interface names should adhere to the following conventions.
The following are examples of proper usage for naming classes and interfaces.
Method names should adhere to the following conventions.
The following are examples of proper usage for naming methods.
The following are examples of proper usage for naming variables.
The names of variables declared class constants ( static final ) and of ANSI constants should be all uppercase with words separated by underscores ( _ ). (ANSI constants should be avoided, for ease of debugging.)
The following are several examples of proper naming of constants.
Fields (instance and class variables) should always have private access. They should only be worked with indirectly, via accessors and mutators ( get and set methods).
The only exception to this rule is the case where the class is essentially a data structure, with no behavior. In other words, if one would have used a struct instead of a class (if Java supported struct ), then it is appropriate to make the fields of the class public.
It is required to use the this object reference when accessing instance variables or calling non-static methods. Java assumes this in contexts where it is omitted; however, its explicit use removes any ambiguity. In addition, since Java is an object-oriented language it is considered good programming style to have all references (excluding local variables) to be prefaced by an object.
The following are several example of correct and incorrect access to instance variables.
A class name is required to access constants, static fields, or static methods. Do not use an object reference. In cases local to the class, do not use this or exclude a reference altogether.
The following are several examples of correct and incorrect access to constants, class variables, and static methods.
Do not assign several variables to the same value in a single statement. It is hard to read.
The following is an example of both incorrect and correct variable assignments.
Do not use the assignment operator in a place where it can be easily confused with the equality operator.
The following is an example of both incorrect and correct use of the assignment operator in a conditional.
Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler.
The following is an example of both incorrect and correct use of the assignment operator.
The following is an example of both incorrect and correct use of parentheses within a conditional.
Wherever possible, avoid multiple return statements in a method. It is good programming practice to have a single exit point from a method; otherwise, debugging can be difficult. If necessary, a temporary variable can be used to track the return value.
The following is an example of using a temporary variable to store the return value for a method rather than have multiple return statements.
Also, try to make the structure of the program match the intent.
The following example shows a case where the use of the if-else statement is extraneous.
The entire previous statement could be written simply as the following.
The following is another example of a case where the use of the if-else statement is extraneous.
The entire previous statement could be written simply as the following.
The following is an example of an acceptable case of more than one return statement for a method.
If a class or interface contains an accessor ( getFoo() or isFoo() ) and mutator ( setFoo() ) pair that have the same access level they should placed adjacent to each other with the accessor placed first in the file.
If a class does not derive directly from any other class, explicitly state in the class declaration that it extends from Object even though Java infers this fact.
Fully-qualified class names (e.g., java.beans.BeanInfo ) should not be used within the code.
The following are exceptions to this rule.
The following is an example of acceptable use of fully-qualified class names.
Use XXX in a comment to flag something that is unconventional or bogus but works. Use FIXME to flag something that is bogus and broken.
The following gives several example of proper use of special comments.
A. Code Example
The following is a complete example of a properly formatted Java class file that properly adheres to the conventions in this document.
This is version 2.1 (10 October 2016) of the document. It consists of minor updates from v2.0, none of which affected the original conventions.
Version 2.0 (09 February 2003) was an update of v1.0 to be more general purpose. It was specifically resurrected for use in several software development classes being taught at St. Edward’s University.
The annals of Version 1.0 (c. 2000) have been lost in time.
The information on this page is for Archive Purposes Only
This page is not being actively maintained. Links within the documentation may not work and the information itself may no longer be valid. The last revision to this document was made on April 20, 1999
10.1 Providing Access to Instance and Class Variables
Don’t make any instance or class variable public without good reason. Often, instance variables don’t need to be explicitly set or gotten-often that happens as a side effect of method calls.
10.2 Referring to Class Variables and Methods
Avoid using an object to access a class (static) variable or method. Use a class name instead. For example:
10.3 Constants
10.4 Variable Assignments
Avoid assigning several variables to the same value in a single statement. It is hard to read. Example:
fooBar.fChar = barFoo.lchar = ‘c’; // AVOID!
Do not use the assignment operator in a place where it can be easily confused with the equality operator. Example:
should be written as
Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler. Example:
d = (a = b + c) + r; // AVOID!
should be written as
10.5 Miscellaneous Practices
10.5.1 Parentheses
It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems. Even if the operator precedence seems clear to you, it might not be to others-you shouldn’t assume that other programmers know precedence as well as you do.
10.5.2 Returning Values
Try to make the structure of your program match the intent. Example:
The information on this page is for Archive Purposes Only
This page is not being actively maintained. Links within the documentation may not work and the information itself may no longer be valid. The last revision to this document was made on April 20, 1999
7.1 Simple Statements
Each line should contain at most one statement. Example:
7.2 Compound Statements
Compound statements are statements that contain lists of statements enclosed in braces » < statements >«. See the following sections for examples.
7.3 return Statements
A return statement with a value should not use parentheses unless they make the return value more obvious in some way. Example:
7.4 if, if-else, if else-if else Statements
The if-else class of statements should have the following form:
7.5 for Statements
A for statement should have the following form:
An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form:
When using the comma operator in the initialization or update clause of a for statement, avoid the complexity of using more than three variables. If needed, use separate statements before the for loop (for the initialization clause) or at the end of the loop (for the update clause).
7.6 while Statements
A while statement should have the following form:
An empty while statement should have the following form:
7.7 do-while Statements
A do-while statement should have the following form:
7.8 switch Statements
A switch statement should have the following form:
Every time a case falls through (doesn’t include a break statement), add a comment where the break 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 break in the default case is redundant, but it prevents a fall-through error if later another case is added.
7.9 try-catch Statements
A try-catch statement should have the following format:
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Java Coding Style Guideline
Version: 2.0
Author: Thibaud LEPRETRE
Greatly inspired by (thanks guys):
Table of Contents
1.1 Why have code conventions
Code conventions are important to programmers for a number of reasons:
For the conventions to work, every person writing software must conform to the code conventions. Everyone.
Example code in this document is non-normative. That is, while the examples are in style guide, they may not illustrate the only stylish way to represent the code. Optional formatting choices made in examples should not be enforced as rules.
2 Source file basics
Use the following file suffixes:
File type
Suffix
Java source
.java
Java bytecode
.class
The source file name consists of the case-sensitive name of the top-level class it contains.
Source files are encoded in UTF-8.
2.4 Special characters
2.4.1 Whitespace characters
Aside from the line terminator sequence, the ASCII horizontal space character ( 0x20 ) is the only whitespace character that appears anywhere in a source file. This implies that:
2.4.2 Special escape sequences
2.4.3 Non-ASCII characters
For the remaining non-ASCII characters, either the actual Unicode character (e.g. β ) or the equivalent Unicode escape (e.g. \u221e ) is used, depending only on which makes the code easier to read and understand.
Tip: in the Unicode escape case, and occasionally even when actual Unicode characters are used, an explanatory comment can be very helpful.
Example
Discussion
String unitAbbrev = «ΞΌs»;
Best: perfectly clear even without a comment.
String unitAbbrev = «\u03bcs»; // «ΞΌs»
Allowed, but there’s no reason to do this.
String unitAbbrev = «\u03bcs»; // Greek letter mu, «s»
Allowed, but awkward and prone to mistakes.
String unitAbbrev = «\u03bcs»;
Poor: the reader has no idea what this is.
return ‘\ufeff’ + content; // byte order mark
Good: use escapes for non-printable characters, and comment if necessary.
Tip: Never make your code less readable simply out of fear that some programs might not handle non-ASCII characters properly. If that should happen, those programs are broken and they must be fixed.
3 Source file structure
A source file consists of, in order:
Exactly one blank line separates each section that is present.
3.1 License or copyright information
If license or copyright information belongs in a file, it belongs here.
3.2 Package statement
The first non-comment line of most Java source files is a package statement.
3.2.1 No line-wrapping
The package statement is not line-wrapped. The section 4.2.1 Line length does not apply to package statements.
3.3 Import statements
3.3.1 No wildcard imports
Wildcard imports, static or otherwise, are not used.
3.3.2 No line-wrapping
The import statement is not line-wrapped. The section 4.2.1 Line length does not apply to import statements.
3.3.3 Ordering and spacing
Import statements are divided into the following groups, in this order, with each group separated by a single blank line:
Within a group there are no blank lines, and the imported names appear in ASCII sort order. (Note: this is not the same as the import statements being in ASCII sort order; the presence of semicolons warps the result.)
3.4 Class and Interface declaration
3.4.1 One top-level class declaration
Each top-level class resides in a source file of its own.
3.4.2 Class member ordering
The ordering of the members of a class can have a great effect on learnability, but there is no single correct recipe for how to do it. Different classes may order their members differently.
What is important is that each class order its members in some logical order, which its maintainer could explain if asked. For example, new methods are not just habitually added to the end of the class, as that would yield «chronological by date added» ordering, which is not a logical ordering.
You can optionally adopt the following arrangement (which place public method before all other to separate API from implementation):
3.4.3 Overloads: never split
When a class has multiple constructors, or multiple methods with the same name, these appear sequentially, with no intervening members.
Moreover keep getter and setter together.
Each time a new block or block-like construct is opened, the indent increases by tab. When the block ends, the indent returns to the previous indent level. The indent level applies to both code and comments throughout the block.
4.1.1 Alignement using 4 spaces
Use 4 spaces for expressing the indentation level and for alignment.
Example using indentation equals to four spaces:
4.1.2 Why not using tabs/smartab?
Avoid lines longer than 120 characters. Except as noted below, any line that would exceed this limit must be line-wrapped, as explained in Section 4.2.2 Wrapping lines.
Exceptions:
4.2.2 Wrapping lines
When line-wrapping, each line after the first (each continuation line) is indented at least +8 (2 times indentation) from the original line.
When there are multiple continuation lines, indentation may be varied beyond +8 (2 times indentation) as desired. In general, two continuation lines use the same indentation level if and only if they begin with syntactically parallel elements.
There is no comprehensive, deterministic formula showing exactly how to line-wrap in every situation. Very often there are several valid ways to line-wrap the same piece of code.
General principles can be used:
Tip: extracting a method or local variable may solve the problem without the need to line-wrap.
Here are some examples of breaking method calls:
Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.
Following 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 8 spaces.
Line wrapping for if statements should generally use the 2 tabs rule, since conventional (1 tab) indentation makes seeing the body difficult. For example:
Here are three acceptable ways to format ternary expressions:
4.3.1 Nonempty blocks
Braces follow the Kernighan and Ritchie style (Egyptian brackets) for nonempty blocks and block-like constructs:
An empty block or block-like construct may be closed immediately after it is opened, with no characters or line break in between ( <> ), unless it is part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else or try/catch/finally ).
For multi-block statement:
4.4.1 Vertical Whitespace
A single blank line appears:
Multiple consecutive blank lines are permitted, but never required (or encouraged).
4.4.2 Horizontal whitespace
Beyond where required by the language or other style rules, and apart from literals, comments and Javadoc, a single ASCII space also appears in the following places only.
This rule never requires or forbids additional space at the start or end of a line; it addresses only interior space.
4.4.3 Horizontal alignment
This practice is permitted, but is never required. It is not even required to maintain horizontal alignment in places where it was already used.
Here is an example without alignment, then using alignment:
Tip: Alignment can aid readability, but it creates problems for future maintenance. Consider a future change that needs to touch just one line. This change may leave the formerly-pleasing formatting mangled, and that is allowed. More often it prompts the coder (perhaps you) to adjust whitespace on nearby lines as well, possibly triggering a cascading series of reformattings. That one-line change now has a «blast radius.» This can at worst result in pointless busywork, but at best it still corrupts version history information, slows down reviewers and exacerbates merge conflicts.
4.5.1.1 One variable per declaration
Every variable declaration (field or local) declares only one variable: declarations such as int a, b; are not used.
Local variables are not habitually declared at the start of their containing block or block-like construct. Instead, local variables are declared close to the point they are first used (within reason), to minimize their scope. Local variable declarations typically have initializers, or are initialized immediately after declaration.
4.5.2 Classes and Interfaces
When coding Java classes and interfaces, the following formatting rules should be followed:
4.6.1 Simple statements
Each line should contain at most one statement. Example:
4.6.2 Compound statements
Compound statements are statements that contain lists of statements enclosed in braces ( < statements >). See the following sections for examples.
4.6.3 return statements
A returnstatement with a value should not use parentheses unless they make the return value more obvious in some way. Example:
The if-else class of statements should have the following form:
4.6.5 for statements
A for statement should have the following forms:
When using the comma operator in the initialization or update clause of aforstatement, avoid the complexity of using more than three variables. If needed, use separate statements before the for loop (for the initialization clause) or at the end of the loop (for the update clause).
An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form:
4.6.6 while statements
A while statement should have the following form:
An empty while statement should have the following form:
4.6.7 do-while statements
A do-while statement should have the following form:
4.6.8 switch statements
A switch statement should have the following form:
Vertical whitespaces are allowed:
As with any other block, the contents of a switch block are indented +4.
After a switch label, a newline appears, and the indentation level is increased +4, exactly as if a block were being opened. The following switch label returns to the previous indentation level, as if a block had been closed.
4.6.8.2 Fall-through: commented
Every time a case falls through (doesnβt include a break statement), add a comment where the break statement would normally be. This is shown in the preceding code example with the for example: // falls through comment.
Every switch statement should include a default case. The break in the default case is redundant, but it prevents a fall-through error if later another case is added.
4.6.9 try-catch statements
A try-catch statement should have the following forms:
A try-catch statement may has multiple redundant catch clause:
4.7 Specific constructs
After each comma that follows an enum constant, a line-break is optional. Additional blank lines (usually just one) are also allowed. This is one possibility:
An enum class with no methods and no documentation on its constants may optionally be formatted as if it were an array initializer (see Section 4.7.3.1 Array initializers).
Since enum classes are classes, all other rules for formatting classes apply Section 4.5.2 Classes and Interfaces.
Annotations applying to a class, method or constructor appear immediately after the documentation block, and each annotation is listed on a line of its own (that is, one annotation per line). Example:
Exception: A single parameterless annotation may instead appear together with the first line of the signature, for example:
There are no specific rules for formatting parameter and local variable annotations.
4.7.3.1 Array initializers
Any array initializer may optionally be formatted as if it were a «block-like construct.» For example, the following are all valid (not an exhaustive list):
4.7.3.2 No C-style array declarations
Comments are not enclosed in boxes drawn with asterisks or other characters.
Class and member modifiers, when present, appear in the order recommended by the Java Language Specification:
4.9 Numeric Literals
4.10 Runtime Exception
RuntimeException or any unchecked exception should not declared on signature since it is misleading to the user of that API.
Declaring in javadoc is recommended if possible.
5.1 Common to all identifiers
5.2 By indentifier type
The prefix of a unique package name is always written in all-lowercase ASCII 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 countries as specified in ISO Standard 3166, 1981.
Package names are all lowercase, with consecutive words simply concatenated together (no underscores). For example,
Class names are written in UpperCamelCase.
There are no specific rules or even well-established conventions for naming annotation types.
Test classes are named starting with the name of the class they are testing, and ending with Test. For example, HashTest or HashIntegrationTest
Method names are written in lowerCamelCase.
5.2.4 Constant names
Constant names use CONSTANT_CASE : all uppercase letters, with words separated by underscores. But what is a constant, exactly?
Every constant is a static final field, but not all static final fields are constants. Before choosing constant case, consider whether the field really feels like a constant. For example, if any of that instance’s observable state can change, it is almost certainly not a constant. Merely intending to never mutate the object is generally not enough. Examples
These names are typically nouns or noun phrases.
5.2.5 Non-constant field names
Non-constant field names (static or otherwise) are written in lowerCamelCase.
5.2.6 Parameter names
Parameter names are written in lowerCamelCase.
One-character parameter names should be avoided.
5.2.7 Local variable names
Local variable names are written in lowerCamelCase, and can be abbreviated more liberally than other types of names.
However, one-character names should be avoided, except for temporary and looping variables.
Even when final and immutable, local variables are not considered to be constants, and should not be styled as constants.
5.2.8 Type variable names
Each type variable is named in one of two styles:
Sometimes there is more than one reasonable way to convert an English phrase into camel case, such as when acronyms or unusual constructs like «IPv6» or «iOS» are present. To improve predictability use the following (nearly) deterministic scheme.
Note that the casing of the original words is almost entirely disregarded. Examples:
Prose form
Correct
Incorrect
«XML HTTP request»
XmlHttpRequest
XMLHTTPRequest
«new customer ID»
newCustomerId
newCustomerID
«inner stopwatch»
innerStopwatch
innerStopWatch
«supports IPv6 on iOS?»
supportsIpv6OnIos
supportsIPv6OnIOS
«YouTube importer»
YouTubeImporter *
* Can also accept YoutubeImporter but not recommended
Note: Some words are ambiguously hyphenated in the English language: for example «nonempty» and «non-empty» are both correct, so the method names checkNonempty and checkNonEmpty are likewise both correct.
6 Programming Practices
6.1 Avoid public class members
Donβt make any instance or class variable public without good reason. Often, instance variables donβt need to be explicitly set or gottenβoften that happens as a side effect of method calls.
One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a struct instead of a class (if Java supported struct ), then itβs appropriate to make the classβs instance variables public.
6.2 Static members: qualified using class
When a reference to a static class member must be qualified, it is qualified with that class’s name, not with a reference or expression of that class’s type.
6.3 Variable Assignments
Avoid assigning several variables to the same value in a single statement. It is hard to read. Example:
Do not use the assignment operator in a place where it can be easily confused with the equality operator. Example:
should be written as
Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler. Example:
should be written as
6.4 Grouping parentheses
It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems. Even if the operator precedence seems clear to you, it might not be to othersβyou shouldnβt assume that other programmers know precedence as well as you do.
6.5 Returning Values
Try to make the structure of your program match the intent. Example:
should instead be written as
should be written as
6.6 Expressions before ‘?’ in the Conditional Operator
6.7 @Override: always used
A method is marked with the @Override annotation whenever it is legal. This includes a class method overriding a superclass method, a class method implementing an interface method, and an interface method respecifying a superinterface method.
6.8 Caught exceptions
When it truly is appropriate to take no action whatsoever in a catch block, the reason this is justified is explained in a comment.
The basic formatting of Javadoc blocks is as seen in this example:
. or in this single-line example:
The basic form is always acceptable. The single-line form may be substituted when there are no at-clauses present, and the entirety of the Javadoc block (including comment markers) can fit on a single line.
One blank line β that is, a line containing only the aligned leading asterisk ( * ) β appears between paragraphs, and before the group of «at-clauses» if present. Each paragraph but the first has
immediately before the first word, with no space after.
7.2 The summary fragment
The Javadoc for each class and member begins with a brief summary fragment. This fragment is very important: it is the only part of the text that appears in certain contexts such as class and method indexes.
7.3 Where Javadoc is used
At the minimum, Javadoc is present for every public class, and every public or protected member of such a class, with a few exceptions noted below.
Other classes and members still have Javadoc as needed. Whenever an implementation comment would be used to define the overall purpose or behavior of a class, method or field, that comment is written as Javadoc instead. (It’s more uniform, and more tool-friendly.)
7.3.1 Exception: self-explanatory methods
7.3.2 Exception: overrides
Javadoc is not always present on a method that overrides a supertype method.
The information on this page is for Archive Purposes Only
This page is not being actively maintained. Links within the documentation may not work and the information itself may no longer be valid. The last revision to this document was made on April 20, 1999
A file consists of sections that should be separated by blank lines and an optional comment identifying each section.
Files longer than 2000 lines are cumbersome and should be avoided.
For an example of a Java program properly formatted, see «Java Source File Example» on page 19.
3.1 Java Source Files
Each Java source file contains a single public class or interface. When private classes and interfaces are associated with a public class, you can put them in the same source file as the public class. The public class should be the first class or interface in the file.
Java source files have the following ordering:
3.1.1 Beginning Comments
All source files should begin with a c-style comment that lists the class name, version information, date, and copyright notice:
3.1.2 Package and Import Statements
The first non-comment line of most Java source files is a package statement. After that, import statements can follow. For example:
3.1.3 Class and Interface Declarations
The following table describes the parts of a class or interface declaration, in the order that they should appear. See «Java Source File Example» on page 19 for an example that includes comments.
The information on this page is for Archive Purposes Only
This page is not being actively maintained. Links within the documentation may not work and the information itself may no longer be valid. The last revision to this document was made on April 20, 1999
Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. Tabs must be set exactly every 8 spaces (not 4).
4.1 Line Length
Avoid lines longer than 80 characters, since they’re not handled well by many terminals and tools.
Note: Examples for use in documentation should have a shorter line length-generally no more than 70 characters.
4.2 Wrapping Lines
When an expression will not fit on a single line, break it according to these general principles:
Here are some examples of breaking method calls:
Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.
Following 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 8 spaces.
Line wrapping for if statements should generally use the 8-space rule, since conventional (4 space) indentation makes seeing the body difficult. For example:
Here are three acceptable ways to format ternary expressions:
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Java Coding Conventions
This document serves the coding standards for source code in Java language. It is intended for use by software engineering teams to employ a common style when writing Java code.
Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.
Source file structure
Exactly one blank line separates each section that is present.
Ordering of class contents
JUnit Tests method ordering
paragraph tag to separate multiple paragraphs.
* Nulla non mollis leo. Aliquam efficitur lectus eros, sit amet ultrices * ex fringilla at. * * @return user issued books */ public Book[] getBooks(User user) < return dao.getBooks(user); >«>
It is a software metric, used to indicate the complexity of a program. It is a quantitative measure of the number of linearly independent paths through a program’s source code. More details to be shared!
One goal of a programming course is for you to learn to write programs that are not only correct but also understandable. These guidelines should help you toward that goal. They will give you a good basis for developing a style of your own as you become a more experienced programmer. This page includes guidelines for Java constructs that will be covered later in the semester. Skim these sections now and read them more carefully later, when the topics are discussed.
Some of these guidelines are standard Java practice, while others are intended to develop good coding habits. When in doubt, choose the alternative that makes the code most obviously correct:
We adhere to Java’s naming conventions. These may seem arbitrary and bizarre if you’re not used to them. Nonetheless, conforming to aesthetic standards of coding is something you’ll need to do in just about any software development workplace, so it’s good practice.
Java class, field, method, and variable names are written in CamelCase: Words are smashed together and the first letter of each word is capitalized. No word separator, like the underscore _, is used.
There is one exception to CamelCase: constants. Constants are in all-caps with words separated by underscores. Constants should also have the keyword final, and they are usually static:
Class and interface names are generally noun or noun phrases and begin with a capital letter:
Method names generally begin with a lowercase letter. A call on a procedure is a statement to do something, so a procedure name is generally a verb phrase that is a command to do something.
A function call yields a value, so a function name is generally a noun phrase that describes the value.
However, a convention in Java is that a function that yields the value of a field (say title) is the name of the field preceded by «get». People are of two minds on this; not everyone thinks it’s a good idea. The name «title» could also be used.
The name of a boolean function is often a verb phrase starting with «is», thus describing what the value means:
Variable names generally start with a lowercase letter.
Variable names should give the reader some hint about what the variable is used for. A well-chosen name, which gives a hint at the meaning of the variable, helps document a program, making it easier to understand. On the other hand, using the names of your friends or flowers that you like as variable names just annoys and makes the program harder to understand. Don’t do that. Also, refrain from using vague names like counter or var or data; instead think about what the variable really is for and use a more concrete name.
There is a tension between writing long descriptive names and very short names. A long name may make it easy to remember what the variable is for, but its length may make the whole program seem long and complicated. It may be difficult to see what a very short name means, but it makes the program short. For example, consider these two statements, which look so different only because of the length of the variable name:
A name can rarely be used to give a complete, precise definition of the entity it names, and a complete definition should always be given where the entity is defined.
Here is a compromise. We tend to use shorter names for parameters and local variables and longer names for fields and static variables. We explain why.
Local variable names. A local variable is a variable that is declared in a method body. Its declaration should be placed as close to its first use as possible. The scope of a local variable is usually short, and its meaning is often obvious either from a comment on its declaration or from the short code in which it is used. Therefore, names of local variables may be short.
Package names are usually all lowercase and consist of nouns.
Use a formatting convention consistently within a class. For example, the position of open braces «<" should be the same throughout the program.
Put only one statement on a line (although there may be exceptional cases where more than one is better). Don’t pack everything together, making a program hard to read.
Make sure that all lines can be read without the need for horizontal scrolling. A mximum of 80 characters per line is recommended.
Indentation is used to make the structure of a program clear. The basic rule is:
We prefer putting an opening curly brace «<" at the end of a line, and not on a line by itself, as shown below. The closing brace ">» appears on its own line, indented as shown below.
There are two reasons for documenting a program well.
First, you, the programmer, need all the help you can get while writing and debugging the program. This means that documentation should be written during the coding/debugging process; it should not be put off until the program is considered finished. The tendency is to wait until the end, and then document. That just means you will make more errors, take more time programming, and end up with more bugs in your program. Get in the habit of documenting a field when you declare it and specifying a method before you write its body. If you decide to change what a method is supposed to do, change its specification first!
You document a program well so that others have an easier time understanding it. A professional programmer is well regarded if their code is easy to maintain by others. A grader of your assignment will be more likely to feel good about you when grading if your program is well documented. So, document your program well.
The Elements of Style, a famous little book on writing style by Cornell Professors W. Strunk, Jr., and E.B. White, contains several rules that are useful for programming as well as writing. Among them are:
Omit needless words. Use the active voice.
Java has three kinds of comments. Comments that start with «//» are one-line comments: the comment ends at the end of the line. Comments that start with «/*» must end with «*/», but they may span many lines.
A Javadoc comment starts with «/**» (and therefore ends with «*/». Javadoc stands for «Java documentation». These comments have a special place in Java and also in Eclipse, when dealing with a Java program. Suppose a method is written like this:
If you now hover the mouse over a call of this function, e.g.
a pop-up window opens with the specification of the method in it! So you get to see preciely what the function call will do and what its preconditions is. Do you see how writing specifications during programming can help you?
Some people have a tendency to put a «//» comment on almost every line. This is generally just noise, making it harder to read the program. Don’t do it. Refrain from commenting lines like this:
Assume that the reader has experience with Java and understands basic statements. Generally speaking, the only kinds of comments needed are those that are mentioned in this section 3 on comments.
The class invariant is the collection of meanings of and constraints on fields of a class. The class invariant is generally placed in comments on each individual field declaration or placed as a single comment before the fields. Here are examples. Note the appearance of constraints, when necessary. We have made them javadoc comments so the Eclipse feature of showing the javadoc comments when an occurrence of the field name is moused over will work.
/** The hour of the day, in 0..23.*/ private int hr;
/** temps[0..numRecorded-1] are the recorded temperatures */ private double[] temps; /** number of temperatures recorded */ private int numRecorded;
If you are not interested in using the javadoc facility in an IDE, since the fields are private, javadoc comments are not necessary. Therefore, you can write the class invariant in a readable style as one-line comments on the same line as the declaration:
private int hr; // The hour of the day, in 0..23.
private double[] temps; // temps[0..numRecorded-1] are the recorded temperatures private int numRecorded; // number of temperatures recorded
The purpose of a constructor is to initialize all fields so that the class invariant is true. Then, when writing a method, you can assume that the class invariant is true when the method is called and write the method body so that it terminates with the class invariant true. Looking often at the class invariant can help prevent mistakes caused by forgetting just what a field means or what its constraints are.
Java has certain conventions for describing the parameters and result of a method. For example, one can write this within a Javadoc specification to describe parameter b and the result
One can certainly use these. However, we have found that a specification can be written more compactly and clearly without using those, and we do not require them. The main guideline is to write the specification as a command to do something, naming all parameters in that command. Examples are given below.
Procedure specifications are generally best written as commands to do something, e.g.
Function specifications are generally written to indicate what to return, e.g.:
The purpose of a constructor is to initialize all fields so that the class invariant is true. We favor writing a constructor specification as illustrated by the following:
A call binarySearch(25, c) will work properly only if 25 is in array c and c is sorted. If not, the method can do anything.
If it doesn’t cost too much, the method can be made more robust by checking that the precondition is true (using a Java assert statement), but it is not necessary.
Similarly, a postcondition is an assertion that will be true upon termination of the method.
Each public class is given in a separate file. The beginning of the file should contain a javadoc comment that explains what the class is for. This can be a simple, short summary. Often, one also puts here information concerning the author, the date of last modification, and so on. Here is an example.
Inner classes and non-public classes that are defined in the same file along with a public class should be specified in a similar fashion.
Just as the sentences of an essay are grouped in paragraphs, so the sequence of statements of the body of a method should be grouped into logical units. Often, the clarity of the program is enhanced by preceding a logical unit by a comment that explains what it does. This comment serves as the specification for the logical unit; it should say precisely what the logical unit does.
The comment for such a logical unit is called a statement-comment. It should be written as a command to do something. Here is an example.
Statement comments must be complete. The comment
Use of blank lines. Place a blank line after the implementation of each statement-comment. In the following example,
// If t is empty, print an error message and return. if (t.length() == 0) < . return false; >
// Store the French translation of t in tFrench. .
Place assertions wherever the code below depends on that assertion being true and the assertion helps the reader understand. One particular use of it can be in a function body that returns in several places. The following illustrates this:
If the is true, nothing is done, but if it is false, execution throws an exception and, generally, the program terminates.
Using the assert statement instead of an assertion-comment has the advantage of catching errors that cause the assertion to be false. Some people advocate leaving assertions in a finished program, for just that reason, unless the boolean expression is so complicated that it ends up slowing down the program execution.
A loop invariant is an assertion that is true before and after each iteration of a loop and is used to prove correctness of the loop (i.e. prove that execution of the loop achieves the desired postcondition). We do not explain loop invariants here. Our purpose is only to show where they are placed in the program.
A loop invariant is placed as a comment just before the loop. Below, we show a loop invariant in the same code written using a while loop and written using a for-loop.
Principle : Declare a variable as close to its first use as possible.
Look at the small example below. Variable temp has been declared first. This causes the reader to ask, «What is temp for? Well, I don’t know.» The reader goes on and sees that there are some statements to swap b and c under certain circumstances and skips them because the reader knows how to write a swap. Well, the reader still doesn’t know what temp is for!
/** Return middle value of b, c, d */ public static int middle(int b, int c, int d) < int temp;
// Swap b, c to put smaller in b if (b > c) < temp= b; b= c; c= temp; >
// < b Use of access modifiers
Modifier
Class
Package
Subclass
World
public
yes
yes
yes
yes
protected
yes
yes
yes
no
package
yes
yes
no
no
private
yes
no
no
no
Problems with the getter/setter terminology
Here is conventional terminology: a getter method is a function that returns the value of a field (and changes nothing); a setter method is a procedure that stores a value in a field.
This terminology has problems, and it is better to use an alternative terminology: creators, observers, and mutators. This pdf file explains it all in one page.
Immutable classes (or objects)
A side effect occurs when evaluation of an expression changes a value. For example, a side effect occurs if evaluation of the following loop condition, which is a call on function f, changes some variable:
Generally, side effects should be avoided. This means, for example, that an assignment statement like
should change no variable other than b. A side-effect that changes something else could be disastrous, unless it is very well documented and the programmer is aware of what is happening. In fact, the theory of proving programs correct tells us that formal proofs of correctness when side effects may occur are far far more complex than when they may not.
Standard paradigms
One does see some standard paradigms that use side effects. For example, below is a loop that reads and prints lines of a BufferedReader br; the loop condition has the side effect of assigning to variable line.
However, we would never write the loop like this, preferring to write it as follows, in a way that has no side effects, even though it is longer that the one above.
Benevolent side effects
There is one class of side effect that is OK. A benevolent side effect is one that changes the state but not in a way that the user can observe. A benevolent side effect can be used to make a program more efficient. Here is an example.
Consider implementing a class that mantains a set of questions-and-answers. When someone asks a question, the corresponding answer is given. The questions-and-answers are implemented in an array, and one has to search the list in linear fashion to find a question. It is better if more frequently asked questions are at the front of the list, so they are more efficiently found. This can be achieved by the following: Whenever a question is asked, move it up one position in the array. This changes the representation of the set of questions-and-answers, but not the set itself; the user cannot notice the change. This is a benevolent side effect.
So if you see that something is deprecated and you have the time, look for the better alternative and use it instead.
Guidelines, Patterns, and code for end-to-end Java applications
Naming Conventions for Enterprise Applications Early Access 2
This document describes the naming conventions that the BluePrints team uses for its sample applications. These conventions pertain to the various components and modules in the Java 2 Platform, Enterprise Edition (J2EE). By applying these conventions, your modules and components will be easier to identify and organize, thus enhancing their maintenance and promoting better coordination on large projects.
All conventions described here are compliant to Code Conventions for the Java Programming Language.
J2EE Application, Module, and Component Names
Description
References in the Code Conventions
Application Name
The application name is used as the application archive name. By default, the application name should be indicative of the application and should be written in all-lowercase ASCII letters. In case of conflict, the application name should be a more specific and descriptive version:
petstore.ear // enterprise archive
or (in case of conflict):
bppetstore.ear // enterprise archive
The application display name (in the application deployment descriptor) is the expanded 1 application name written in mixed cases:
or (in case of conflict):
Follows naming conventions for packages
Enterprise JavaBeans (EJB) Module Name
The module name is used as the EJB archive name. By default, the module name should be based on the package name and should be written in all-lowercase ASCII letters. In case of conflict, the module name should be a more specific version (including other part of the package name):
The module display name (in the EJB deployment descriptor) is the expanded module name written in mixed cases:
or (in case of conflict):
BluePrintsPetStoreJAR
Web Module Name
The module name is used as the web archive name. By default, the module name should be based on the package name and should be written in all-lowercase ASCII letters. In case of conflict, the module name should be a more specific version (including other part of the package name):
Midlet client archive:
com.sun.j2ee.blueprints. petstore petstore.war // Web archive petstore-applet-client.jar // Applet archive
or (in case of conflict):
bppetstore.war // Web archive
bppetstore-applet-client.jar // Applet archive
The module display name (in the Web deployment descriptor) is the expanded module name written in mixed cases:
or (in case of conflict):
Follows naming conventions for packages
Component Name
The component is the base name of the EJB or web component class name and should be written in mixed case with the first letter of each internal word capitalized.
ContactInfoBean
Follows naming conventions for classes
2. EJB Component Names
This includes naming conventions for the different parts of an enterprise bean. Wherever these names go in the deployment descriptor, it has been specified. The conventions listed here does not mention the type of the bean explicitly, except for the display name in the deployment descriptor.
References in the Code Conventions
Entity Bean
Local interface: or Local
Local home interface: Home or LocalHome
Remote interface: Remote
Remote home interface: RemoteHome
Implementation class: Bean
Primary key implementation:
Name in the EJB deployment descriptor: Bean
Display name in the EJB deployment descriptor:
Follows naming conventions for classes
Session Bean
Local interface: or Local
Local home interface: Home or LocalHome
Remote interface: Remote
Remote home interface: RemoteHome
Implementation class: Bean
Name in the EJB deployment descriptor: Bean
Display name in the EJB deployment descriptor: SB
Follows naming conventions for classes
Message Driven Bean
Implementation class: Bean
Name in the deployment descriptor: Bean
Display name in the EJB deployment descriptor: MDB
Follows naming conventions for classes
3. Web Component Names
This includes naming conventions for Servlets and JavaServer Pages TM and their related artifacts like Servlet filters and JavaServer Pages TM tags
References in the Code Conventions
Servlet
Implementation class: Servlet
Name in the Web deployment descriptor: component-name
Display name in the Web deployment descriptor: Servlet
Filter
Implementation: Filter
Name in the Web deployment descriptor: component-name
Display name in the Web deployment descriptor: Filter
Listener
For classes implement following listener interfaces:
Name in the Web deployment descriptor: component-name
Display name in the Web deployment descriptor: Listener
JavaServer Pages TM
JSP (file) name should always begin with a lower-case letter. The name may consists of multiple words, in which case the words are placed immediately adjacent and each word commences with an upper-case letter. A JSP name can be just a simple noun or a short sentence. A verb-only JSP name should be avoided, as it does not convey sufficient information to developers.
Here’re conventions for other file types.
4. Web service Names
This includes naming conventions for Web service clients and endpoints and the necessary configuration files.
References in the Code Conventions
Service Name
The service name is the base name of the EJB or JAX-RPC endpoint class name and should be written in mixed case with the first letter of each internal word capitalized.
WeatherService
Follows naming conventions for classes
EJB service endpoint
Service endpoint interface : SEI
Service implementation class : Bean
Follows naming conventions for classes
JAX-RPC service endpoint
Service endpoint interface : SEI
Service implementation class : Impl
Follows naming conventions for classes
JAX-RPC message handler
Client side handler : ClientHandler
Server side handler : ServerHandler
Follows naming conventions for classes
Configuration files
WSDL file :
5. Reference Names
EJB reference name is the logical name you use in your source code for a JNDI lookup of the home interface of the referenced bean. This name also apperas as the value of the ejb-ref-name element within the ejb-ref element in the deployment decriptor of the referencing component.
Web service reference name is the name used by Web service clients for a JNDI lookup to obtain a reference to a Web service. This name also apperas as the value of the service-ref-name element within the service-ref element in the deployment decriptor of the referencing component.
Environment entry names are the names used by a component for a JNDI lookup of some customizable parameters. T his name also apperas as the value of the env-entry-name element within the env-entry element in the deployment decriptor of the component.
All the reference names are relative to java:comp/env.
Description
References in the Code Conventions
EJB References
By default, the EJB reference name should be based on the component name. The component name should be written in mixed case with the first letter of each internal word capitalized
If you have only the local or the remote interface, you may want to use just ejb/ and leave out the suffixes. If you have both kind of interfaces, you may want to use the suffix only for the remote interfaces since typically you will have fewer of them.
In case of conflict, the EJB reference name should be a more specific version of the component name.
Say you have a Customer EJB module ( customer-ejb.jar ) which contains the ContactInfoBean component ( ContactInfoBean.class). In this case, the Customer module will refer to the ContactInfo module in the following way:
In case, the Customer module had two ContactInfo objects: one for customer, and one for supplier; the names will be:
ejb/CustomerContactInfo ejb/SupplierContactInfo
Web service references
The Web service reference name should be based on the service name. The service name should be written in mixed case with the first letter of each internal word capitalized
service/CreditCardService
Resource References
The resource reference name should be based on the resource name. The resource name should be written in mixed case with the first letter of each internal word capitalized
jms/ [Queue|Topic] Examples:
mail/ resource-qualifier Example:
jms/ Factory or jms/ [Queue|Topic]Factory Examples:
The paramter name should be written in mixed case with the first letter of each internal word capitalized. Parameters may be grouped under a common context name.
param/CatalogDAOClass param/event/ActionEvent
6. Database Names
This applies to the databases that map to CMP entity beans. This convention does not apply when you are mapping CMP entities to a prexisting schema, since the database entities already have names.
References in the Code Conventions
Database
If your organization already has a convention for database naming, follow that. Otherwise, name CMP databases after the application.
For example: PetStore DB
7. XML Document Names
Description
References in the Code Conventions
XML Documents
One possible notation:
Element names follow the code convention of class names and should be written in mixed case with the first letter of each internal word capitalized.
Attribute names follow the code convention of variable names and should be written in mixed case with a lower case first letter.
Enumerated Attribute values follow the code convention of constants and should be written in upper case with words seperated by underscores.
Another possible notation:
Element names are written in lower case with words separeted by a hyphen ‘-‘.
Attribute names follow the code convention of variable names and should be written in mixed case with a lower case first letter.
Enumerated attribute values follow the code convention of constants and should be written in upper case with words seperated by underscores.
Any other notation as long as it is consistent across your application