Существуют соглашения, по поводу использования Java библиотек и инструментов для Android. В некоторых случаях соглашения могут быть изменены, например, в таких как использование старого кода, который, возможно, использует неодобренный паттерн или библиотеку.
Правила Java стиля
Программы гораздо проще поддерживать, когда все файлы имеют согласованный стиль. Мы следуем стандартному стилю программирования на Java, определенному Sun в их Code Conventions for the Java Programming Language, с несколькими исключениями и дополнениями. Данное руководство по стилю является подробным и всесторонним, а также широко используется Java сообществом.
Правила языка Java
Не игнорируйте исключения
Возможно, вам захочется написать код, который игнорирует исключения, например:
Не перехватывайте обобщенные исключения
Иногда бывает заманчиво полениться с обработкой исключений и написать что-то вроде этого:
Вам не следует так делать. Суть в том, что возможно появление исключения, которого вы не ожидали и, в итоге, ошибка будет отлавливаться на уровне приложения. То есть, если кто-то добавит новый тип исключения, то компилятор не сможет вам помочь понять, что это другая ошибка.
Существуют редкие исключения из этого правила: определенный тестовый код, или код верхнего уровня, где вы хотите перехватывать все типы ошибок (для того, чтобы предотвратить их отображение в пользовательском интерфейсе, или чтобы продолжить какую-то пакетную задачу).
Финализаторы
Что это: Финализаторы — это способ запускать программный код перед тем как объект собирается сборщиком мусора. За: могут быть полезны при очистке, в особенности внешних ресурсов. Против: нет никаких гарантий того, когда будет вызван финализатор, и, вообще, будет ли он вызван.
Решение: Мы не используем финализаторы. В большинстве случаев, всё то, что вам нужно от финализатора, вы сможете сделать при помощи обработки исключений. Если вам действительно нужен финализатор, то объявите метод close() и задокументируйте, когда он точно будет вызываться.
Импорты
Групповой символ в импортах
Что это: Когда вы хотите использовать класс Bar из пакета foo, то есть два способа сделать это:
За #1: Потенциально уменьшает количество возможных операторов импорта. За #2: Делает явным то, какой класс на самом деле используется. Делает код более удобочитаемым для тех, кто его поддерживает.
Решение: Используйте стиль #2 для импорта любого Android кода. Явное исключение делается для стандартных библиотек (java.util.*, java.io.*, и т.п) и для кода модульного тестирования (junit.framework.*).
Комментарии/Javadoc
Каждый файл должен иметь объявление об авторских правах в самом начале. Далее идут объявления операторов package и import, причем каждый блок разделяется пустой строкой. За ними следуют объявления класса или интерфейса. Опишите, что делает класс в Javadoc-комментариях.
Каждый класс и нетривиальный public метод должен содержать Javadoc, по крайней мере с одной фразой, описывающей что он делает. Фраза должна начинаться с описательного глагола 3-го лица. Примеры:
Вам не нужно описывать Javadoc для тривиальных get и set методов, таких как setFoo(), если ваш Javadoc говорит только «sets Foo». Если метод делает что-то более сложное (например, соблюдение неких ограничений, или если его действия имеют важный эффект вне его самого), тогда его обязательно нужно задокументировать. И если это не просто объяснение того, что означает Foo, то вам также следует его задокументировать.
Вообще, любой метод, который вы написали получает пользу от Javadoc, неважно public он или нет. Public методы являются частью API, и поэтому они требуют описания в Javadoc.
Для написания Javadoc’ов вам следует придерживаться Sun Javadoc conventions.
Короткие методы
Методы должны быть небольшими и решающими конкретную задачу настолько, насколько это возможно. Однако, понятно, что иногда большие методы бывают целесообразны, так что нет строгого ограничения на длину метода. Если метод превышает 40 строк, то вам, возможно, стоит подумать о том, можно ли его разбить на части, не нарушив структуры программы.
Локальные переменные
Область видимости локальных переменных должна сводиться к минимуму. Делая это, вы улучшаете читаемость и поддерживаемость кода, а также уменьшаете вероятность ошибок. Каждая переменная должна объявляться в самом глубоком блоке, который окружает все возможные места использования переменной.
Локальные переменные должны объявляться в том месте, где впервые необходимо её использовать. Почти каждая локальная переменная нуждается в инициализаторе. Если вы еще не знаете, как точно инициализировать переменную, то вам следует отложить её объявление, пока вы это не узнаете.
Существует одно исключение, касательно блока try-catch. Если переменная инициализируется при помощи оператора return метода, который выбрасывает проверяемое исключение, то она должна инициализироваться в блоке try. Если же переменная должна использоваться вне блока try, тогда она объявляется перед ним, неважно, знаете ли вы как её точно нужно инициализировать:
Но даже этот случай можно обойти при помощи инкапсуляции блока try-catch в методе.
Переменные в циклах должны объявляться внутри самого оператора, если только нет непреодолимой причины этого не делать.
Импорты
Отступы
мы используем 4 пробела для блоков. Мы никогда не используем табуляцию. Мы используем 8 пробелов для переноса строк, включая вызовы функций и присваивания, например правильно так:
Названия полей
Фигурные скобки
Для открывающих фигурные скобок не выделяется отдельная строка, они находятся в той же строке, что и код перед ними:
Мы требуем фигурные скобки для оператора условия. Исключением является, когда оператор условия и его тело помещаются в одну строку. То есть можно писать так:
Длина строки
Каждая строка текста в коде должна быть не длиннее 100 символов. Исключение: если комментарий содержит пример команд, или URL (удобнее использовать copy/paste). Исключение: строки импорта могут быть длиннее 100 символов, так как люди редко на них смотрят. Также это упрощает написание инструментов.
Сокращения в именах
Рассматривайте сокращения и аббревиатуры как слова. Имена более удобочитаемы:
Хорошо
Плохо
XmlHttpRequest
XMLHTTPRequest
getCustomerId
getCustomerID
Этот стиль также применяется, когда сокращение и аббревиатура — это полное имя:
Хорошо
Плохо
class Html
class HTML
String url;
String URL;
long id;
long ID;
Стиль TODO
Используйте комментарии TODO для кода, который является временным, краткосрочным, или хорошим, но не идеальным. Комментарий должен включать в себя «TODO:», например:
Если ваш комментарий имеет вид «В будущем сделать что-то», то убедитесь, что он включает в себя конкретную дату (1 января 2011 года), или конкретное событие «Удалить после выхода версии 2.1».
Согласованность
Если вы изменяете код, то потратьте минуту на то, чтобы посмотреть на код вокруг вас и определить его стиль. Если в нем используются пробелы, то и вам следует их использовать. Если комментарии содержат небольшой набор звездочек, то и вам следует их использовать.
Весь смысл рекомендаций к стилю кода в создании общей лексики, чтобы люди концентрировались на том, что они говорят, вместо того как они говорят. Мы представляем глобальные правила стиля, чтобы люди знали эту лексику. Но локальный стиль также важен. Если код, который вы добавляете в файл выглядит резко отличным от того, что был, то это выбросит будущего читателя из его ритма и будет мешать ему понимать структуру. Старайтесь избегать этого.
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.
Уважаемые посетители! Если вы обнаружили в каком-нибудь слове ошибку! Выделите это слово и нажмите Ctrl+Enter одновременно! Заранее спасибо за сотрудничество!
Контакты
Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.
Соглашения по оформлению кода Java (Java Code Conventions)
Данный перевод не претендует на пальму первенства или как наиболее точный перевод! Думаю таких переводов в сети довольного много, может многие из них переведены куда лучше этого =)
Этот перевод я делал для себя в целях ознакомления с данным документом, да и правилам оформления кода в целом. В этом переводе отчасти использовались материалы с этого перевода.
Для себя я старался его сделать максимально удобоваримым для понимания и использования в дальнейшем =) По этому если кто хочет его использовать где-то в других местах, то не забываем указывать ссылку на этот материал или сайт http://www.magnumblog.space;)
А вообще пользуйтесь на здоровье.
1.1 Зачем нужны условные обозначения кода
Соглашения по оформлению кода важны для программистов по ряду причин:
1.2 Выражение признательности
В этом документе содержатся стандарты по оформлению кода на языка Java, представленные в спецификации от Sun Microsystems. Основные вклады от Питера Кинга, Патрика Нотона, Майка ДеМони, Джонни Канервы, Кэти Уолрата и Скотта Хоммеля.
По вопросам, связанным с адаптацией, модификацией или распространением этого документа, пожалуйста, прочитайте наше уведомление об авторских правах по адресу http://java.sun.com/docs/codeconv/html/Copyright.doc.html.
Комментарии к этому документу должны быть отправлены в нашу форму обратной связи по адресу http://java.sun.com/docs/forms/sendusmail.html.
В этом разделе перечислены наиболее часто используемые имена файлов и их расширения.
2.1 Расширения файлов
В программах написанных на Java используются следующие расширения файлов:
Тип файла
Расширение
Для исходного кода
.java
Для байт-кода
.class
2.2 Общие имена файлов
Часто используемые имена файлов включают:
Имя файла
Применение
GNUmakefile
Зарезервированное имя для создаваемых файлов. Мы используем gnumake для создания нашего программного обеспечения.
README
Зарезервированное имя файла в котором содержится информация о файлах находящихся в той же директории.
Файл состоит из разделов, которые должны быть разделены пустыми строками и необязательным комментарием, идентифицирующим каждую секцию.
Файлы длиной более 2000 строк являются громоздкими и их следует избегать.
Пример форматирования файла с исходным кодом Java приведен в разделе «Пример файла с исходным кодом Java».
3.1 Файлы с исходным кодом Java
Каждый файл с исходным кодом Java содержит один class с ключевым словом public или интерфейс. Когда классы с ключевым словом private и интерфейсы связанны с public классом, то их можно поместить в тот же файл с иходным кодом, что и public класс. Класс с ключевым словом public должен быть размещен как первый класс или интерфейс в файле.
Файлы с исходным кодом Java имеют следующий порядок:
3.1.1 Начальный комментарий
Все файлы с исходным кодом должны начинаться с комментария в стиле языка C, в котором перечислены авторы программы, дата, сведения об авторских правах, а так же кратко описание того, что делает программа. Для примера:
3.1.2 Операторы Package и Import
Первая строка без комментария в файле с исходным кодом Java это оператор package. После нее следует оператор import. Для примера:
3.1.3 Объявления классов и интерфейсов
В следующей таблице описаны части объявления класса или интерфейса в том порядке, в котором они должны отображаться. Образец с комментариями приведен в «Примере файла с исходным кодом Java»
Часть объявления класса/интерфейса
Заметки
Комментарий для документации по классам и интерфейсам (/**. */)
Смотрите в «Комментарии для документации» какая информация должна содержатся в этом комментарии
Оператор class или interface
Если необходимо, то указать комментарий реализации класса/интерфейса (/*. */)
Здесь содержится любая дополнительная информация по классу или интерфейсу, которая не подходит для документирующего комментария.
(static) Переменные класса
Сначала переменные класса public, затем protected, и только потом private
Переменные экземпляра
Сперва public, затем protected, и только потом private.
Конструкторы
Методы
Методы должны быть сгрупированным по функциональности, а не по области или доступности. Для примера метод класса private может находится между двумя public методами экземпляра. Цель в облегчении чтения и понимания кода.
В качестве единицы отступов следует использовать четыре пробела. Точная конструкция отступа (пробелы или символы табуляции) не указана. Табуляция должна быть установлена ровно каждые 8 пробелов (а не 4).
4.1 Длина строки
Избегайте строк длиннее 80 символов, так как они не обрабатываются многими терминалами и инструментами.
4.2 Перенос строки
Если выражение не помещается на одной строке, разбейте его в соответствии с этими общими принципами:
Несколько примеров переноса строки в вызовах методов:
Ниже приведены два примера переноса арифметического выражения. Первое предпочтительнее, так как разрыв происходит вне выражения в скобках, которое находится на более высоком уровне.
Отступы в строках с оператором if следует применить по правилу 8-ми пробелов, так как если использовать стандартные 4-ре пробела, то поиск тела оператора будет затруднителен. Например:
Вот три приемлемых способа форматирования тернарных выражений:
Комментарии кода используются для описания отдельных строк/блоков кода или целого алгоритма. Комментарии для документирования используются, чтобы описать спецификацию кода (его интерфейс), не зависящую от его реализации. Комментарии для документирования делают для разработчиков, которые будут использовать ваши программы (библиотеки классов) не имея их исходного кода.
Комментарии нужны, чтобы описать код или пояснить моменты, которые сложно понять непосредственно из кода. Комментарии должны содержать лишь ту информацию, которая необходима для чтения и понимания кода программы. Например информацию о том, как откомпилировать связанный пакет или в какой директории он находится не стоит описывать в комментарии.
Обсуждение нетривиальных или неочевидные решений необходимо, но не нужно описывать то, что и так ясно из кода. Такие «избыточные» комментарии очень быстро могут стать неактуальными. В общем, следует избегать любых комментариев, которые могут стать неактуальными по мере развития кода.
Примечание: Частое использование комментариев иногда говорит о низком качество кода. Когда вы чувствуете необходимость добавить комментарий, попробуйте переписать код, чтобы он стал понятнее.
Комментарии не должны быть заключены в большие квадраты, помеченные звездочками или другими символами. Например:
Комментарии не должны содержать специальных символов, таких как символ конца страницы или backspace.
5.1 Формат реализации комментариев
В программах могут использоватся 4 вида комментариев: блочные, однострочные, прицепные и комментарии до конца строки.
5.1.1 Блок комментариев
Блочные комментарии используются для описания файлов, методов, структур данных и алгоритмов. Так же их следует использовать в начале каждого файла и перед каждым методом. Они также могут использоваться в других местах, например, внутри методов. Блочные комментарии внутри функции или метода должны иметь отступ на том же уровне, что и код, который они описывают.
Перед блочным комментарием следует оставлять пустую строку, чтобы визуально отделить его от кода. Каждая строка блочного комментария (кроме первой) должна начинаться с символа «*«.
Если блочный комментарий начинается с «/*-«, это означает в данном блоке используется особое форматирование, которое нельзя потерять (Такой блок не будет переформатирован средствами автоформатирования). Например:
Примечание: Если вы не используете средства автоформатирования, вам не обязательно использовать «/*-» в коде, но можете сделать это на случай того, что кто-то другой может запустить средства автоформатирования на вашем коде.
5.1.2 Однострочный комментарий
Однострочные комментарии (короткие комментарии) можно писать в одной строке используя отступ на уровне соответствующего блока кода, который он описывает. Если комментарий не помещается в одну строку, следует использовать блочный комментарий (смотрите «Блок комментариев»). Однострочному комментарию должна предшествовать пустая строка. Вот пример однострочного комментария в Java-коде (смотрите «Комментарии для документации»):
5.1.3 Прицепные комментарии
Очень короткий комментарий можно расположить на той же строке, что и описываемый код. При этом его следует сдвинуть вправо настолько, чтобы он не сливался с кодом. Если в одном блоке кода присутствует более одного такого комментария, их начало должно быть на одном уровне.
Старайтесь избегать комментирования каждой строчки кода подобным образом.
Пример прицепных комментариев в Java коде (смотрите также «Комментарии для документирования»):
5.1.4 Комментарии в конце строки
Символами // начинается комментарий, который продолжится до следующей строки (новой строки). Он может занимать всю строку или только ее часть. Его не следует использовать для многострочных комментариев, однако его можно использовать, чтобы закомментировать несколько строк кода. Рассмотрим пример всех трех вариантов его использования:
5.2 Комментарии для документирования
Примечание: смотрите «Пример файла с исходным кодом Java» для примеров форматов комментариев, описанных здесь.
Для получения дополнительной информации смотрите «Как написать комментарии к документу для Javadoc«, который включает в себя информацию о тегах комментариев документа (@return, @param, @see):
Для получения большей информации о документирующих комментариях и Javadoc, посетите домашнюю страницу Javadoc:
Документирующие комментарии описывают Java классы, интерфейсы, конструкторы, методы и поля. Каждый комментарий помещается в ограничители /**. */, один комментарий на один элемент API. Такой комментарий должен располагаться непосредственно перед объявлением:
Обратите внимание, что классы и интерфейсы не имеют отступов, в отличии от их членов. Первая строка документирующего комментария (/**) для классов и интерфейсов не имеет отступов; каждая последующая строка документирующего комментария имеет 1 пробел (для вертикального выравнивания звездочек). Члены класса, включая конструкторы, имеют 4 пробела для первой строки документирующего комментария и 5 для остальных.
Если необходимо предоставить информацию о классе, интерфейсе, переменной или методе, не принадлежащую к документации, используйте блочный (смотрите раздел 5.1.1) или однострочный (смотрите раздел 5.1.2) комментарий непосредственно после объявления. Например, детали о реализуемом классе должны идти в таком комментарии в блоке реализации, а не в документирующем комментарии.
Документирующий комментарий не должен располагаться внутри блока реализации метода или конструктора, потому что Java связывает документирующий комментарий с первым после него объявлением.
6.1 Количество объявлений в строке
Рекомендуется использовать одно объявление на строку, так как это облегчает комментирование. Другими словами:
Ни в коем случае нельзя объявлять переменные и функции в одной строке. Например:
Не помещайте переменные разных типов (имеется в виду не тип самих переменных, а тип данных которые в них хранятся) в одну строку. Например:
Примечание: В приведенных выше примерах используется один пробел между типом и идентификатором. Другой приемлемой альтернативой является использование табуляции для выравнивания инеднтивикторов в одину линию (использование клавиши Tab которая равна обычно 4-м пробелам), например:
6.2 Размещение
Размещайте объявления только в начале блоков (блоком является любой код, заключенный в фигурные скобки «<«» и «>«). Не ждите объявления переменных до их первого использования; Это может запутать неопытного программиста и затруднить переносимость кода в пределах области.
Единственным исключением из этого правила являются индексы циклов for, которые в Java могут быть объявлены в операторе for:
Избегайте локальных объявлений, перекрывающих объявления более высокого уровня. Например, не объявляйте одну и ту же переменную перед блоком кода и во внутреннем блоке:
6.3 Инициализация
Старайтесь инициализировать локальные переменные там, где вы их объявляете. Единственная причина не инициализировать переменную в месте её объявления — если её начальное значение зависит от некоторых предварительных вычислений.
6.4 Объявления классов и интерфейсов
При написании Java классов и интерфейсов необходимо соблюдать следующие правила форматирования:
7.1 Простые операторы
Каждая строка должна содержать не более одного оператора. Например:
Не используйте запятую для группировки нескольких операторов, даже если это видно невооруженным глазом. Например:
7.2 Составные операторы
7.3 Оператор return
Оператор return, возвращающий значение, не должен использовать скобки, если только их использование не сделает возвращаемое значение более понятным. Например:
7.4 Операторы if, if-else, if-else-if-else
Группа операторов (как и еденичное использование) if-else должна иметь следующий вид:
Примечание: операторы if всегда должны использоватся с фигурными скобками » «. Избегайте следующей формы:
7.5 Оператор цикла for
Оператор цикла for должен иметь следующий вид:
Пустой оператор цикла for (тот, в котором вся работа выполняется в инициализации, условии и итерации) должен иметь следующий вид:
При использовании оператора запятой в блоке инициализации или итерации оператора цикла for избегайте использования более чем трех переменных. Если необходимо, используйте отдельные операторы перед циклом for (для случая блока инициализации) или в конце цикла (для случая блока итерации).
7.6 Оператор цикла while
Оператор цикла while должен иметь следующий вид:
Пустой оператор цикла while должен иметь следующий вид:
7.7 Оператор цикла do-while
Оператор цикла do-while должен иметь следующий вид:
7.8 Оператор switch
Оператор switch должен иметь следующую форму:
Каждый раз, когда выбор проваливается (не включая оператор break), добавьте комментарий, где обычно находится оператор break. Это показано в предыдущем примере кода с комментарием /* провал */.
Каждый оператор switch должен включать выбор по умолчанию (default). Оператор break в выборе по умолчанию лишний, но он предотвращает возникновение ошибки, если позже еще один выбор добавится.
7.9 Оператор try-catch
Оператор try-catch должн иметь следующий формат:
8.1 Пустые строки
Пустые строки улучшают читабельность, выделяя разделы кода, которые логически связаны между собой.
Две пустые строки всегда должны использоваться в следующих случаях:
Одна пустая строка всегда должна использоваться в следующих случаях:
8.2 Расстановка пробелов
Разделяющие пробелы должны ставиться при следующих обстоятельствах:
Обратите внимание, что пробел не должен использоваться между именем метода и его открывающей скобкой. Это помогает отличать ключевые слова от вызовов метода.
Правила, приведенные в данном разделе, являются основополагающими. Более конкретные правила приведены в таблице:
10.1 Обеспечение доступа к экземпляру и переменным класса
Одним из примеров уместного использования public полей может быть случай, когда класс описывает лишь структуру данных, без какого-либо поведения. Другими словами, если бы вы могли использовать struct вместо class (если бы Java поддерживал struct), тогда можно сделать переменные экземпляра класса public.
10.2 Обращение к переменным и методам класса
Избегайте использование объекта для доступа к статическим полям и методам класса. Вместо этого используйте имя класса. Например:
10.3 Константы
Численные константы (литералы) не должны кодироваться напрямую, за исключением -1, 0 и 1, которые могут использоваться в циклах для управления счетчиком.
10.4 Примеры присваивания значение переменным и операторам и т.д.
Избегайте присваивания значения некоторым переменным в одном выражении. Это усложняет чтение. Например:
Не используйте оператор присваивания в местах, где он может быть легко спутан с оператором сравнения. Например:
лучше написать так:
Не используйте вложенные присваивания, пытаясь ускорить скорость выполнения программы. Это работа компилятора, и, кроме того, на самом деле редко помогает. Например:
дожно быть написано так:
10.5 Различные приёмы программирования
10.5.1 Круглые скобки
10.5.2 Возврат значения
Попробуйте сделать структуру вашей программы понятной. Например:
вместо этого следует записать так:
лучше записать так:
10.5.3 Выражения перед ‘?’ в условном операторе
Если выражение содержит бинарный оператор, находящийся перед тернарным оператором ?:, он должен быть заключен в скобки. Например:
10.5.4 Специальные комментарии
Используйте XXX в комментарии для того, чтобы показать, что этот код неправильный, но работает. Используйте FIXME для того, чтобы показать, что код неправильный и не работает.
11.1 Пример файла с исходным кодом Java
Следующий пример показывает как форматировать файл с исходным кодом Java, содержащим отдельный класс. Интерфейсы форматируются отдельно. Для более подробного изучения прочтите «Объявление классов и интерфейсов» и «Документирующие комментарии«.
Версию для оффлайн чтения можно найти в моем репозитории Github
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:
Статья об именах переменных, классов и методов, скобках, комментариях, форматировании кода и других правилах хорошего тона, принятых в языке Javа.
В языке Java, как и во многих других языках программирования, есть неофициальные, но принятые сообществом разработчиков соглашения по оформлению кода. Давайте попробуем разобраться, что это такое, как работает и почему важно.
Зачем нужен единый стиль кода
Java Code Style — это рекомендации и соглашения о стиле кода, собранные вместе. Например:
Регламентируется множество вещей, связанных с оформлением исходного текста программ, и приводятся требования, которые необходимо учитывать. Почему возникли эти стандарты?
Причины, по которым разработчики пришли к таким соглашениям, логичны и просты:
Использование общепринятых соглашений по оформлению позволяет сделать код более аккуратным, избежать ошибок, связанных с разными стилями написания у людей, работающих над одним проектом.
Форматирование на практике
Стиль не играет роли для компьютера, но важен для чтения кода человеком. Наше зрение устроено так, что сперва получает и анализирует образы, а только затем мы вдаёмся в детали. А если блоки исходного текста унифицированы, разработчик понимает, что перед ним за конструкция, даже не вникая в сам код.
Файлы с исходным кодом хранятся в кодировке UTF-8.
Символы пустого места
Кроме символов перевода строки, только ASCII-пробел (0x20) встречается в файлах. Это означает:
Для любого символа, который имеет специальную escape-последовательность (b, \t, \n, \f, \r, «, ‘ и \), эта последовательность используется вместо соответствующего octal (например \012) или Unicode-символа (например \u000a).
Для остальных не-ASCII символов, используется или сам Unicode-символ (например ∞) или соответствующий Unicode escape-символ (например \u221e). Выбор символа зависит только о того, насколько легко код с ним читать и понимать, хотя Unicode escape-символы вне строковых литералов и комментариев вставлять не рекомендуется.
Совет: в случае использования Unicode escape-символа, и иногда даже когда используется сам Unicode символ, поясняющие комментарии могут быть полезны.
Пример
Комментарии
String unitAbbrev = «μs»;
Лучший вариант: все ясно даже без комментария
String unitAbbrev = «\u03bcs»; // «μs»
Разрешается, но нет причины так делать
String unitAbbrev = «\u03bcs»; // Greek letter mu, «s»
Разрешается, но странно выглядит и неустойчиво к ошибкам
String unitAbbrev = «\u03bcs»;
Плохо: читатель не поймет, что это такое
return ‘\ufeff’ + content; // byte order mark
Хорошо: используется escape-символ для непечатных символов, и есть коммент
Совет: не делайте ваш код менее читаемым просто из боязни, что какая-либо программа не сможет обработать не-ASCII символы верно. Если такое случается, значит программа работает неправильно и должна быть починена.
Файл с исходным кодом состоит из:
Секции разделяются одной пустой линией.
Имя пакета не разделяется переносом строки. Заданная нами длина строки не распространяется на строку с именем пакета.
Использование wildcard и static импортов не рекомендуется. Исключение: если ситуация оправдана, и все испортируемые методы и константы близки по смыслу к классу в данном файле.
Импорт не разделяется переносом строки. Заданная нами длина строки не распространяется на строку с импортом класса.
Нет специальных правил на порядок импортов. Придерживаемся стиля, заданного по-умолчанию в используемой всеми IDE.
Каждый класс верхнего уровня находится в отдельном файле с его именем.
Порядок расположения членов класса
Члены классы располагаются в таком порядке:
Не разрываем последовательность перегруженных методов
Если у класса есть несколько конструкторов или методов с одним и тем же именем, они располагаются друг за другом, без включения других полей/методов
Ставим скобки, даже если это необязательно
Непустые блоки: стиль K & R
Скобки ставятся в соответствии со стилем Кернигана и Ричи (Египетские скобки) для непустых блоков:
Исключения делаются для Enum-классов.
Пустые блоки не укорачиваем
Ставим перевод строки и комментарий, даже если тело блока пустое:
Отступы слева для блоков
Каждый раз, когда мы открываем новый блок, отступ увеличивается на 2 пробела. Когда блок заканчивается, отступ возвращается до прежнего значения. Отступ применяется и для комментариев в блоке.
Одно выражение на строку
Каждое выражение или оператор заканчивается переводом строки.
Длина строки в коде имеет лимит в 120 символов. Кроме исключений, любая строка больше лимита должна быть разбита на 2 строки, как описано в разделе Перенос строки.
При переносе строк, каждая перенесенная строка после самой первой отступает слева на 8 пробелов от начальной строки. В общем случае, отступ для 2 перенесенных строк будет одинаковым только если начинаются с синтаксически параллельных конструкций.
Вертикальное пустое место
Одна пустая строка стоит:
Несколько пустых строк подряд разрешается, но не обязательно.
Горизонтальное пустое место
Одиночный ASCII-пробел встречается в следующих местах (помимо требования синтаксиса языка, литералов, комментов и javadoc):
Правила относятся к пробелам внутри строки, а не отступам (оговариваются в другом разделе).
Горизонтальное выравнивание не используется
Выравнивание может улучшить читаемость, но создает проблемы для дальнейшей поддержки. Допустим, последующее изменение затрагивает всего 1 строку. Часто такое изменение сбивает выравнивание, что выглядит уже не так хорошо. Но чаще разработчик стремится поддержать порядок выравнивания и меняет оступы в других строках, инициируя каскадную серию форматирований. Это однострочное изменение теперь имеет «радиус поражения». Это бесполезная работа, также это ухудшает читаемость истории версий, замедляет ревьюеров и затрудняет разрешение merge-конфликтов.
После каждой запятой после определения Enum-константы нужен перевод строки. Дополнительно допускается пустая строка после этого. Пример:
Enum-классы в остальном подчиняются общим правилам оформления классов.
В каждой строке определяется только одна переменная
Каждое определение (поле или локальная переменная) состоит только из одной переменной: определения вида int a, b; не используются.
Переменные определяются по мере надобности
Локальные переменные не обязательно должны определятся в начале блока или метода. Вместо этого, он определяются как можно ближе к месту их первого использования, чтобы уменьшить область действия переменной. Локальные переменные как правило сразу инициализируются.
Квадратные скобки ставятся рядом с типом, а не самой переменной: String[] args, но не String args[].
Внутри скобок в switch-блоке располагаются одна или несколько групп операторов. Каждая группа содержит одну или несколько меток (например FOO: или default:), за которой следуют операторы.
Как и с другими блоками, оступ для содержимого составляет +2 пробела. После метки стоит перевод строки, и отступ снова увеличивается на +2, как в случае с открытием нового блока. Следующая метка находится на предыдущем уровне, как будто блок закрылся.
Провалы в следующие метки: не используются
Исключения делается только для пустых меток (пример выше с case 1:). Для каждого switch должна быть default-метка, даже если она не содержит кода.
Аннотации, применяемые к классу, методу или конструктору ставятся сразу после блока документации, и находятся на отдельной строке (по одной аннотации на строке). Отступ слева после аннотации не увеличивается. Пример:
Нет специальных правил для форматирования аннтотаций на параметрах, локальных переменных, типах.
Модификаторы классов и методов ставятся в порядке, рекомендованном Java Language Specification:
public protected private abstract default static final transient volatile synchronized native strictfp
Числовые литералы типа long используют большую букву L, никогда не используется нижний регистр (чтобы избежать путаницы с цифрой 1). Например, надо писать 3000000000L вместо 3000000000l.
Правила для всех идентификаторов
Имена пакетов пишутся в нижнем регистре, слова просто последовательно конкатенируются друг с другом (без нижних подчеркиваний). Например, com.example.deepspace, а не com.example.deepSpace или com.example.deep_space.
Имена классов пишутся в UpperCamelCase.
Нет специальных правил для именования аннотаций.
Тестовые классы начинаются с имени класса, который они тестируют, и заканчиваются на Test. Например, HashTest или HashIntegrationTest.
Имена методов пишутся в lowerCamelCase.
Имена констант используют CONSTANT_CASE: все буквы в верхнем регистре, слова отделяются нижним подчеркиванием. Но что есть константа?
Каждая константа является static final полем, но не все static final поля являются константами. Прежде чем именовать переменную константой, подумайте реально ли она является ей. Например, если видимое состояние экземпляра обьекта может измениться, это точно не константа. Просто мысли о том, что объект не будет меняться в процессе работы, не достаточно. Примеры:
Имена неконстантных полей
Имена параметров пишутся в lowerCamelCase. Односимвольных имен параметров в публичных методах следует избегать.
Имена локальных переменных
Имена локальных переменных пишутся в lowerCamelCase. Даже когда они final и immutable, локальные переменные не надо путать с константами, и именовать их как константы.
Имена переменных типов
Каждая переменная типа именуется одним из 2 способов:
Определение Camel Case
Иногда есть несколько способов конвертировать английскую фразу в camel case, например для аббревиатур или необычных имен типа «IPv6» или «iOS». Чтобы имя было предсказуемо, предлагается такая схема.
Примите во внимание, что регистр букв в оригинальных словах не принимается во внимание. Примеры:
Оригинальная фраза
Правильно
Неправильно
«XML HTTP request»
XmlHttpRequest
XMLHTTPRequest
«new customer ID»
newCustomerId
newCustomerID
«inner stopwatch»
innerStopwatch
innerStopWatch
«supports IPv6 on iOS?»
supportsIpv6OnIos
supportsIPv6OnIOS
«YouTube importer»
YouTubeImporter
YoutubeImporter
Примечание: некоторые слова имеют несколько написаний через дефис в английском языке, например оба «nonempty» и «non-empty» верны. Таким образом, имена методов checkNonempty и checkNonEmpty тоже оба верны.
@Override: всегда используется
Метод всегда помечается аннотацией @Override, если это верно с точки зрения языка. Это включает в себя:
Исключение: @Override можно опустить, если метод родителя обьявлен как @Deprecated.
Перехватываемые исключения: не игнорируются
Кроме случая, описываемого ниже, очень редко является корректным ничего не делать в ответ на перехваченное исключение (типовые способы: логгировать его, если же обьявлено «невозможным», выбросить заново как AssertionError).
Когда реально ничего не надо делать в catch-блоке, причина указывается в поясняющем комментарии:
Исключение: в тестах, перехваченное исключение может игнорироваться без комментария, если имя переменной начинается с expected. Это часто встречается, когда надо убедиться, что тестируемый код бросает исключение нужного типа, поэтому комментарий излишен.
Статические члены класса: указываются через имя класса
Когда нужно указать или сослаться на статическое поле или метод класса, оно определяется с именем класса, а не с ссылкой на обьект или выражение, возвращающее объект типа этого класса.
Finalizers: не используются
Совет: не делайте этого. Если позарез надо, сначала прочитайте и поймите Effective Java Item 7, «Avoid Finalizers», а после этого не делайте этого.
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.
Уважаемые посетители! Если вы обнаружили в каком-нибудь слове ошибку! Выделите это слово и нажмите Ctrl+Enter одновременно! Заранее спасибо за сотрудничество!
Контакты
Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.
Соглашения по оформлению кода Java (Java Code Conventions)
Данный перевод не претендует на пальму первенства или как наиболее точный перевод! Думаю таких переводов в сети довольного много, может многие из них переведены куда лучше этого =)
Этот перевод я делал для себя в целях ознакомления с данным документом, да и правилам оформления кода в целом. В этом переводе отчасти использовались материалы с этого перевода.
Для себя я старался его сделать максимально удобоваримым для понимания и использования в дальнейшем =) По этому если кто хочет его использовать где-то в других местах, то не забываем указывать ссылку на этот материал или сайт http://www.magnumblog.space;)
А вообще пользуйтесь на здоровье.
1.1 Зачем нужны условные обозначения кода
Соглашения по оформлению кода важны для программистов по ряду причин:
1.2 Выражение признательности
В этом документе содержатся стандарты по оформлению кода на языка Java, представленные в спецификации от Sun Microsystems. Основные вклады от Питера Кинга, Патрика Нотона, Майка ДеМони, Джонни Канервы, Кэти Уолрата и Скотта Хоммеля.
По вопросам, связанным с адаптацией, модификацией или распространением этого документа, пожалуйста, прочитайте наше уведомление об авторских правах по адресу http://java.sun.com/docs/codeconv/html/Copyright.doc.html.
Комментарии к этому документу должны быть отправлены в нашу форму обратной связи по адресу http://java.sun.com/docs/forms/sendusmail.html.
В этом разделе перечислены наиболее часто используемые имена файлов и их расширения.
2.1 Расширения файлов
В программах написанных на Java используются следующие расширения файлов:
Тип файла
Расширение
Для исходного кода
.java
Для байт-кода
.class
2.2 Общие имена файлов
Часто используемые имена файлов включают:
Имя файла
Применение
GNUmakefile
Зарезервированное имя для создаваемых файлов. Мы используем gnumake для создания нашего программного обеспечения.
README
Зарезервированное имя файла в котором содержится информация о файлах находящихся в той же директории.
Файл состоит из разделов, которые должны быть разделены пустыми строками и необязательным комментарием, идентифицирующим каждую секцию.
Файлы длиной более 2000 строк являются громоздкими и их следует избегать.
Пример форматирования файла с исходным кодом Java приведен в разделе «Пример файла с исходным кодом Java».
3.1 Файлы с исходным кодом Java
Каждый файл с исходным кодом Java содержит один class с ключевым словом public или интерфейс. Когда классы с ключевым словом private и интерфейсы связанны с public классом, то их можно поместить в тот же файл с иходным кодом, что и public класс. Класс с ключевым словом public должен быть размещен как первый класс или интерфейс в файле.
Файлы с исходным кодом Java имеют следующий порядок:
3.1.1 Начальный комментарий
Все файлы с исходным кодом должны начинаться с комментария в стиле языка C, в котором перечислены авторы программы, дата, сведения об авторских правах, а так же кратко описание того, что делает программа. Для примера:
3.1.2 Операторы Package и Import
Первая строка без комментария в файле с исходным кодом Java это оператор package. После нее следует оператор import. Для примера:
3.1.3 Объявления классов и интерфейсов
В следующей таблице описаны части объявления класса или интерфейса в том порядке, в котором они должны отображаться. Образец с комментариями приведен в «Примере файла с исходным кодом Java»
Часть объявления класса/интерфейса
Заметки
Комментарий для документации по классам и интерфейсам (/**. */)
Смотрите в «Комментарии для документации» какая информация должна содержатся в этом комментарии
Оператор class или interface
Если необходимо, то указать комментарий реализации класса/интерфейса (/*. */)
Здесь содержится любая дополнительная информация по классу или интерфейсу, которая не подходит для документирующего комментария.
(static) Переменные класса
Сначала переменные класса public, затем protected, и только потом private
Переменные экземпляра
Сперва public, затем protected, и только потом private.
Конструкторы
Методы
Методы должны быть сгрупированным по функциональности, а не по области или доступности. Для примера метод класса private может находится между двумя public методами экземпляра. Цель в облегчении чтения и понимания кода.
В качестве единицы отступов следует использовать четыре пробела. Точная конструкция отступа (пробелы или символы табуляции) не указана. Табуляция должна быть установлена ровно каждые 8 пробелов (а не 4).
4.1 Длина строки
Избегайте строк длиннее 80 символов, так как они не обрабатываются многими терминалами и инструментами.
4.2 Перенос строки
Если выражение не помещается на одной строке, разбейте его в соответствии с этими общими принципами:
Несколько примеров переноса строки в вызовах методов:
Ниже приведены два примера переноса арифметического выражения. Первое предпочтительнее, так как разрыв происходит вне выражения в скобках, которое находится на более высоком уровне.
Отступы в строках с оператором if следует применить по правилу 8-ми пробелов, так как если использовать стандартные 4-ре пробела, то поиск тела оператора будет затруднителен. Например:
Вот три приемлемых способа форматирования тернарных выражений:
Комментарии кода используются для описания отдельных строк/блоков кода или целого алгоритма. Комментарии для документирования используются, чтобы описать спецификацию кода (его интерфейс), не зависящую от его реализации. Комментарии для документирования делают для разработчиков, которые будут использовать ваши программы (библиотеки классов) не имея их исходного кода.
Комментарии нужны, чтобы описать код или пояснить моменты, которые сложно понять непосредственно из кода. Комментарии должны содержать лишь ту информацию, которая необходима для чтения и понимания кода программы. Например информацию о том, как откомпилировать связанный пакет или в какой директории он находится не стоит описывать в комментарии.
Обсуждение нетривиальных или неочевидные решений необходимо, но не нужно описывать то, что и так ясно из кода. Такие «избыточные» комментарии очень быстро могут стать неактуальными. В общем, следует избегать любых комментариев, которые могут стать неактуальными по мере развития кода.
Примечание: Частое использование комментариев иногда говорит о низком качество кода. Когда вы чувствуете необходимость добавить комментарий, попробуйте переписать код, чтобы он стал понятнее.
Комментарии не должны быть заключены в большие квадраты, помеченные звездочками или другими символами. Например:
Комментарии не должны содержать специальных символов, таких как символ конца страницы или backspace.
5.1 Формат реализации комментариев
В программах могут использоватся 4 вида комментариев: блочные, однострочные, прицепные и комментарии до конца строки.
5.1.1 Блок комментариев
Блочные комментарии используются для описания файлов, методов, структур данных и алгоритмов. Так же их следует использовать в начале каждого файла и перед каждым методом. Они также могут использоваться в других местах, например, внутри методов. Блочные комментарии внутри функции или метода должны иметь отступ на том же уровне, что и код, который они описывают.
Перед блочным комментарием следует оставлять пустую строку, чтобы визуально отделить его от кода. Каждая строка блочного комментария (кроме первой) должна начинаться с символа «*«.
Если блочный комментарий начинается с «/*-«, это означает в данном блоке используется особое форматирование, которое нельзя потерять (Такой блок не будет переформатирован средствами автоформатирования). Например:
Примечание: Если вы не используете средства автоформатирования, вам не обязательно использовать «/*-» в коде, но можете сделать это на случай того, что кто-то другой может запустить средства автоформатирования на вашем коде.
5.1.2 Однострочный комментарий
Однострочные комментарии (короткие комментарии) можно писать в одной строке используя отступ на уровне соответствующего блока кода, который он описывает. Если комментарий не помещается в одну строку, следует использовать блочный комментарий (смотрите «Блок комментариев»). Однострочному комментарию должна предшествовать пустая строка. Вот пример однострочного комментария в Java-коде (смотрите «Комментарии для документации»):
5.1.3 Прицепные комментарии
Очень короткий комментарий можно расположить на той же строке, что и описываемый код. При этом его следует сдвинуть вправо настолько, чтобы он не сливался с кодом. Если в одном блоке кода присутствует более одного такого комментария, их начало должно быть на одном уровне.
Старайтесь избегать комментирования каждой строчки кода подобным образом.
Пример прицепных комментариев в Java коде (смотрите также «Комментарии для документирования»):
5.1.4 Комментарии в конце строки
Символами // начинается комментарий, который продолжится до следующей строки (новой строки). Он может занимать всю строку или только ее часть. Его не следует использовать для многострочных комментариев, однако его можно использовать, чтобы закомментировать несколько строк кода. Рассмотрим пример всех трех вариантов его использования:
5.2 Комментарии для документирования
Примечание: смотрите «Пример файла с исходным кодом Java» для примеров форматов комментариев, описанных здесь.
Для получения дополнительной информации смотрите «Как написать комментарии к документу для Javadoc«, который включает в себя информацию о тегах комментариев документа (@return, @param, @see):
Для получения большей информации о документирующих комментариях и Javadoc, посетите домашнюю страницу Javadoc:
Документирующие комментарии описывают Java классы, интерфейсы, конструкторы, методы и поля. Каждый комментарий помещается в ограничители /**. */, один комментарий на один элемент API. Такой комментарий должен располагаться непосредственно перед объявлением:
Обратите внимание, что классы и интерфейсы не имеют отступов, в отличии от их членов. Первая строка документирующего комментария (/**) для классов и интерфейсов не имеет отступов; каждая последующая строка документирующего комментария имеет 1 пробел (для вертикального выравнивания звездочек). Члены класса, включая конструкторы, имеют 4 пробела для первой строки документирующего комментария и 5 для остальных.
Если необходимо предоставить информацию о классе, интерфейсе, переменной или методе, не принадлежащую к документации, используйте блочный (смотрите раздел 5.1.1) или однострочный (смотрите раздел 5.1.2) комментарий непосредственно после объявления. Например, детали о реализуемом классе должны идти в таком комментарии в блоке реализации, а не в документирующем комментарии.
Документирующий комментарий не должен располагаться внутри блока реализации метода или конструктора, потому что Java связывает документирующий комментарий с первым после него объявлением.
6.1 Количество объявлений в строке
Рекомендуется использовать одно объявление на строку, так как это облегчает комментирование. Другими словами:
Ни в коем случае нельзя объявлять переменные и функции в одной строке. Например:
Не помещайте переменные разных типов (имеется в виду не тип самих переменных, а тип данных которые в них хранятся) в одну строку. Например:
Примечание: В приведенных выше примерах используется один пробел между типом и идентификатором. Другой приемлемой альтернативой является использование табуляции для выравнивания инеднтивикторов в одину линию (использование клавиши Tab которая равна обычно 4-м пробелам), например:
6.2 Размещение
Размещайте объявления только в начале блоков (блоком является любой код, заключенный в фигурные скобки «<«» и «>«). Не ждите объявления переменных до их первого использования; Это может запутать неопытного программиста и затруднить переносимость кода в пределах области.
Единственным исключением из этого правила являются индексы циклов for, которые в Java могут быть объявлены в операторе for:
Избегайте локальных объявлений, перекрывающих объявления более высокого уровня. Например, не объявляйте одну и ту же переменную перед блоком кода и во внутреннем блоке:
6.3 Инициализация
Старайтесь инициализировать локальные переменные там, где вы их объявляете. Единственная причина не инициализировать переменную в месте её объявления — если её начальное значение зависит от некоторых предварительных вычислений.
6.4 Объявления классов и интерфейсов
При написании Java классов и интерфейсов необходимо соблюдать следующие правила форматирования:
7.1 Простые операторы
Каждая строка должна содержать не более одного оператора. Например:
Не используйте запятую для группировки нескольких операторов, даже если это видно невооруженным глазом. Например:
7.2 Составные операторы
7.3 Оператор return
Оператор return, возвращающий значение, не должен использовать скобки, если только их использование не сделает возвращаемое значение более понятным. Например:
7.4 Операторы if, if-else, if-else-if-else
Группа операторов (как и еденичное использование) if-else должна иметь следующий вид:
Примечание: операторы if всегда должны использоватся с фигурными скобками » «. Избегайте следующей формы:
7.5 Оператор цикла for
Оператор цикла for должен иметь следующий вид:
Пустой оператор цикла for (тот, в котором вся работа выполняется в инициализации, условии и итерации) должен иметь следующий вид:
При использовании оператора запятой в блоке инициализации или итерации оператора цикла for избегайте использования более чем трех переменных. Если необходимо, используйте отдельные операторы перед циклом for (для случая блока инициализации) или в конце цикла (для случая блока итерации).
7.6 Оператор цикла while
Оператор цикла while должен иметь следующий вид:
Пустой оператор цикла while должен иметь следующий вид:
7.7 Оператор цикла do-while
Оператор цикла do-while должен иметь следующий вид:
7.8 Оператор switch
Оператор switch должен иметь следующую форму:
Каждый раз, когда выбор проваливается (не включая оператор break), добавьте комментарий, где обычно находится оператор break. Это показано в предыдущем примере кода с комментарием /* провал */.
Каждый оператор switch должен включать выбор по умолчанию (default). Оператор break в выборе по умолчанию лишний, но он предотвращает возникновение ошибки, если позже еще один выбор добавится.
7.9 Оператор try-catch
Оператор try-catch должн иметь следующий формат:
8.1 Пустые строки
Пустые строки улучшают читабельность, выделяя разделы кода, которые логически связаны между собой.
Две пустые строки всегда должны использоваться в следующих случаях:
Одна пустая строка всегда должна использоваться в следующих случаях:
8.2 Расстановка пробелов
Разделяющие пробелы должны ставиться при следующих обстоятельствах:
Обратите внимание, что пробел не должен использоваться между именем метода и его открывающей скобкой. Это помогает отличать ключевые слова от вызовов метода.
Правила, приведенные в данном разделе, являются основополагающими. Более конкретные правила приведены в таблице:
10.1 Обеспечение доступа к экземпляру и переменным класса
Одним из примеров уместного использования public полей может быть случай, когда класс описывает лишь структуру данных, без какого-либо поведения. Другими словами, если бы вы могли использовать struct вместо class (если бы Java поддерживал struct), тогда можно сделать переменные экземпляра класса public.
10.2 Обращение к переменным и методам класса
Избегайте использование объекта для доступа к статическим полям и методам класса. Вместо этого используйте имя класса. Например:
10.3 Константы
Численные константы (литералы) не должны кодироваться напрямую, за исключением -1, 0 и 1, которые могут использоваться в циклах для управления счетчиком.
10.4 Примеры присваивания значение переменным и операторам и т.д.
Избегайте присваивания значения некоторым переменным в одном выражении. Это усложняет чтение. Например:
Не используйте оператор присваивания в местах, где он может быть легко спутан с оператором сравнения. Например:
лучше написать так:
Не используйте вложенные присваивания, пытаясь ускорить скорость выполнения программы. Это работа компилятора, и, кроме того, на самом деле редко помогает. Например:
дожно быть написано так:
10.5 Различные приёмы программирования
10.5.1 Круглые скобки
10.5.2 Возврат значения
Попробуйте сделать структуру вашей программы понятной. Например:
вместо этого следует записать так:
лучше записать так:
10.5.3 Выражения перед ‘?’ в условном операторе
Если выражение содержит бинарный оператор, находящийся перед тернарным оператором ?:, он должен быть заключен в скобки. Например:
10.5.4 Специальные комментарии
Используйте XXX в комментарии для того, чтобы показать, что этот код неправильный, но работает. Используйте FIXME для того, чтобы показать, что код неправильный и не работает.
11.1 Пример файла с исходным кодом Java
Следующий пример показывает как форматировать файл с исходным кодом Java, содержащим отдельный класс. Интерфейсы форматируются отдельно. Для более подробного изучения прочтите «Объявление классов и интерфейсов» и «Документирующие комментарии«.
Версию для оффлайн чтения можно найти в моем репозитории Github
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
В данном документе описаны стандарты написания кода на языке программирования Java в корпорации Google. Исходный код Java считается соответствующим этим стандартам тогда и только тогда, когда он удовлетворяет всем описанным в документе правилам.
Затронутые в руководстве темы касаются не только эстетической стороны форматирования кода, но и других типов соглашений или стандартов кодирования. Тем не менее, данный документ концентрируется в первую очередь на определении строгих правил, которым мы повсеместно следуем, и не дает рекомендаций, которые могут быть неверно реализованы (как человеком, так и машинными инструментами).
1.1 Терминология
В рамках этого руководства определены следующие термины:
1.2 Примечание к руководству
Примеры кода в данном документе не демонстрируют единственно верный стилистический подход к его форматированию, хотя и используются в нашем руководстве.
2. Исходный файл. Основы
2.1 Имя файла
2.2 Кодировка файла: UTF-8
Для файлов с кодом используется кодировка UTF-8.
2.3 Специальные символы
2.3.1 Символы пробела
Помимо последовательности символов конца строки, горизонтальный символ пробела ASCII (0×20) является единственным символом-разделителем, встречающимся в исходном файле. Это означает, что:
2.3.2 Специальные экранирующие последовательности
Для каждого символа, для которого существует специальная экранирующая последовательность (\b, \t, \n, \f, \r, \», \’ и \\), предпочтительнее использовать именно ее вместо соответствующего ей восьмеричного значения (например, \012) или кода Unicode (например, \u000a).
2.3.3 Символы не из таблицы ASCII
Для символов не из таблицы ASCII используется символ Unicode (например, ∞) или эквивалентная экранирующая последовательность (например, \u221e). Выбор отдается в пользу тех символов, которые делают код более понятным и читаемым.
При использовании символов экранирования в кодировке Unicode и в тех случаях, когда применяются действующие символы Unicode, убедительно рекомендуем такой код сопровождать объясняющими комментариями
Пример
Примечание
String unitAbbrev = «μs»
Отлично: прекрасно воспринимается даже без комментария
Допускается, но неуклюже и может привести к ошибкам
String unitAbbrev = «\u03bcs»
Плохо: читающий понятия не имеет, что это такое
return ‘\ufeff’ + content // знак порядка байтов
Хорошо: используйте экранирование для непечатаемых символов и комментируйте при необходимости
Никогда не делайте ваш код менее читаемым только из опасения, что некоторые программы не смогут правильно обработать символы не из таблицы ASCII. Если такое происходит, такие программы работают неверно и их нужно исправить
3. Структура исходного файла
Исходный файл состоит из следующих элементов (в указанном порядке):
3.1 Информация о лицензии или авторских правах, если имеется
Информация о лицензии или авторских правах должна быть размещена в том файле, к которому она относится.
3.2 Объявление пакета
Пакет объявляется без переноса строки. Ограничение на ширину строки (Раздел 4.4) на объявление пакета не распространяется.
3.3 Объявления импортов
3.3.1 Символ подстановки при объявлении импортов
Символ * (подстановки) при объявлении импортов, статических или нет, не используется.
3.3.2 Перенос строки
Импорты объявляются без переноса строки. Ограничение на ширину строки на них не распространяется.
3.3.3 Упорядочивание и интервал
Импорты упорядочиваются следующим образом:
Внутри каждого блока импортируемые классы следуют в порядке сортировки ASCII-символов.
3.3.4 Статический импорт вложенных классов
Статический импорт не используется для статических вложенных классов. Такие классы импортируются с объявлением обычного импорта.
3.4 Объявление класса
3.4.1 Объявляется ровно один класс верхнего уровня
Каждый класс верхнего уровня располагается в своем исходном файле.
3.4.2 Упорядочивание содержимого класса
Порядок, выбираемый при расположении членов и блоков инициализации класса, может оказать большое влияние на легкость понимания кода. Так или иначе, для этого не существует простого и правильного рецепта; разные классы могут упорядочивать свое содержимое по-разному.
Важно то, чтобы у каждого класса был такой логический порядок расположения содержимого, который позволил бы программисту, читающему код, объяснить его.
3.4.2.1 Перегруженный код не должен быть разделен
Когда у класса есть несколько конструкторов или методов с одинаковым именем, они должны располагаться последовательно, без вставок другого кода между ними.
4. Форматирование
Терминология
Тело класса, метода или конструктора относится к блочной конструкции.
Обратите внимание, что согласно Разделу 4.8.3.1, любой инициализатор массива также может рассматриваться как блочная конструкция.
4.1 Фигурные скобки
4.1.1 Фигурные скобки используются везде, где они могут быть использованы
Фигурные скобки используются в if, else, for, while и do-while, даже если тело выражения пустое или содержит лишь одну строку кода.
4.1.2 Непустые блоки: стиль K & R
Фигурные скобки ставятся согласно стилю Кернигана и Ритчи («Египетские скобки») для непустых блоков и блочных конструкций (для наглядности мы решили добавить немного кода, демонстрирующего данные правила — примечание переводчика):
Некоторые исключения для перечислений приведены в Разделе 4.8.1
4.1.3 Пустые блоки могут быть сжатыми
Пустой блок или пустая блочная конструкция может следовать стилю K & R (как описано в Разделе 4.1.2). Также возможно, чтобы такой блок был закрыт сразу же после открытия, без символов или разрыва строки внутри <>. Это правило не относится к случаю, когда блок является частью многоблочного выражения, которое содержит if-else или try-catch-finally.
4.2 Два пробела для отступа
Каждый раз, когда открывается новый блок или блочная конструкция, смещение вправо увеличивается на два пробела. Когда блок заканчивается, начало следующей строки кода смещается на предыдущий уровень смещения. Уровень смещения применяется как к блоку, так и к комментариям в этом блоке (см. пример в Разделе 4.1.2).
4.3 Одно выражение на каждую строку
Каждое выражение завершается переходом на новую строку.
4.4 Ограничение ширины строки в 100 символов
Java-код имеет ограничение в 100 символов по ширине строки. Под «символом» понимается любой из элементов Unicode. За исключением случаев, описанных ниже, каждая строка с превышением ограничения по ширине, должна быть перенесена так, как это объяснено в Разделе 4.5.
4.5 Перенос строки
Терминология
Когда код, который в другом случае мог бы быть расположен на одной строке, разделяется на несколько строк, это явление называется переносом строки.
Не существует общепринятой однозначной формулы, определяющей, как именно надо делать перенос строки в каждой ситуации. Очень часто существует несколько способов переноса строки с одним и тем же фрагментом кода.
Обычно перенос делается во избежание переполнения строки по ширине. Но даже если код остался бы в пределах разрешенной ширины, то и он, по решению автора, может быть перенесен на новую строку.
Выделение вспомогательного метода или локальной переменной может решить проблему переполнения строки по ширине без переноса кода
4.5.1 Где делать перенос
Первое указание по переносу строки гласит: предпочтительнее делать перенос на более высоком синтаксическом уровне. Также:
1. Когда строка разрывается не на операторе присваивания, разрыв делается перед символом.
Это правило также применимо к следующим «оператороподобным» символам:
Это также применимо к двоеточию для цикла for-each.
3. Имя метода или конструктора при переносе строки остается присоединенным к открывающей скобке «(»
4. Запятая «,» при переносе строки остается с элементом, который ей предшествует
5. Строка никогда не переносится непосредственно у стрелки лямбда-выражения, кроме случаев, когда его тело состоит из одного выражения без фигурных скобок:
Главная цель переноса строки — добиться ясности кода, но не обязательно наименьшего количества строк
4.5.2 Смещение продолжения строки на 4 и более пробелов
При переносе строки каждая следующая ее подстрока (каждое продолжение строки) смещается как минимум на 4 пробела относительно предыдущей.
Когда продолжений строки несколько, смещение может варьироваться в пределах 4 пробелов по желанию автора. По общему правилу, два продолжения строки могут иметь одинаковое смещение тогда и только тогда, когда они начинаются с синтаксически параллельных элементов.
В Разделе 4.6.3 даются указания по использованию различного количества пробелов для выравнивания элементов кода относительно предыдущих строк.
4.6 Пробелы и отступы
4.6.1 Отступы
Одна пустая строка всегда ставится:
1. Между следующими друг за другом членами или инициализаторами класса: полями, конструкторами, методами, вложенными классами, статическими и динамическими блоками инициализации
Пустая строка также может быть использована повсеместно для повышения читаемости кода, например, между выражениями для организации кода в логические подразделы. Пустая строка перед первым членом класса, или блоком инициализации, или после последнего члена, или блока инициализации класса не приветствуется, но и не возбраняется.
Несколько последовательных пустых строк делать разрешается, но это не необходимо и не приветствуется.
4.6.2 Пробелы
Помимо требований самого языка или прочих правил данного документа, а также не считая литералов и комментариев (в т.ч. Javadoc), одиночные пробелы из таблицы ASCII могут присутствовать только в следующих местах:
1. При разделении любого зарезервированного слова, такого как if, for или catch, и открывающей круглой скобки «(», которая следует за ним
2. При разделении любого зарезервированного слова, такого как else или catch, и закрывающей фигурной скобки «>», которая следует за ним
3. Перед любой открывающей фигурной скобкой «<», за исключением двух ситуаций:
Это правило также применимо к следующим операторам:
6. По обе стороны от двойной косой черты «//» при создании комментария в той же строке кода. Здесь разрешены, но не необходимы несколько пробелов
7. Между объявлением типа и именем переменной: 8. Опционально: внутри скобок инициализатора массива new int[] <5, 6>и new int[] < 5, 6 >— оба варианта верные
9. Между аннотацией типа и [] или…
Это правило не требует наличия или отсутствия пробелов в начале или конце строки; оно относится лишь к внутренним пробелам.
4.6.3 Горизонтальное выравнивание не требуется никогда
Терминология
Горизонтальное выравнивание — это практика добавления различного числа дополнительных пробелов в вашем коде с целью сделать так, чтобы определенные элементы были расположены под другими элементами с предыдущей строки.
Эта практика разрешена, но ее использование не требуется данным руководством. Также нет необходимости поддерживать соблюдение выравнивания в тех участках кода, где оно уже было применено.
Пример с выравниванием и без него:
Выравнивание способствует читаемости кода, но создает проблемы с поддержкой такого кода в будущем. Допустим, требуется изменить только одну строку. Это изменение может исказить форматирование ранее принятого кода, что допускается. Но, скорее всего, программист (возможно, вы) начнет корректировку количества пробелов на рядом стоящих строках, что, возможно, запустит целую череду исправлений. Изменение одной строки может активировать «взрывную волну» из бессмысленного труда (в худшем случае). Или, в лучшем случае, приведет к искажению информации в истории версий, ухудшит чтение кода и обострит конфликты слияния.
4.7 Группирующие скобки рекомендованы
Допускается не ставить группирующие скобки только тогда, когда автор кода и рецензент согласны в том, что нет разумной вероятности, что код будет неверно истолкован без скобок, и при этом скобки не облегчили бы его чтение. Нет причины полагать, что каждый, кто читает код, помнит наизусть всю таблицу приоритетов использования операторов Java.
4.8 Особые конструкции
4.8.1 Классы-перечисления
После каждой запятой, которая следует за константой перечисления, разрыв строки необязателен. Дополнительные пустые строки (обычно только одна) также допускаются. Вот пример такого кода:
Код класса-перечисления без методов и комментариев, описывающих его константы, может быть представлен, как инициализатор массива (см. Раздел 4.8.3.1):
Так как перечисления — это классы, для них следует применять все прочие правила, применимые к классам.
4.8.2 Объявления переменных
4.8.2.1 Одна переменная на одно объявление
Каждая переменная (поле или локальная) объявляется только по одной за раз: такие объявления, как int a, b; не используются.
Исключение: Множественные объявления переменных допускаются в заголовке цикла for.
4.8.2.2 Объявляйте переменные тогда, когда они нужны
Локальные переменные необязательно должны объявляться в начале блока или блочной конструкции. Наоборот, локальные переменные необходимо объявлять непосредственно перед местом их первого использования, чтобы минимизировать область их действия. Обычно локальные переменные инициализируются в момент объявления, или же сразу после него.
4.8.3 Массивы
4.8.3.1 Инициализаторы массивов могут быть «блочными»
Любой массив может быть инициализирован так, как если бы он был блочной конструкцией. К примеру, весь следующий код допустим (список примеров не полный):
4.8.3.2 Никаких объявлений массивов в стиле языка С
Квадратные скобки ставятся после типа, а не после переменной: String[] args, а не String args[].
4.8.4 Оператор switch
Терминология
Внутри блока switch располагается одна или более групп операторов. Каждая группа состоит из одной или более меток (как case FOO:, так и default:), за которыми следует один или более операторов (или, в случае последней группы, ни одного или более).
4.8.4.1 Смещение
Как и в случае с любым другим блоком, содержимое блока switch смещается на 2 пробела.
После метки блока switch делается перенос строки, а смещение увеличивается на 2 пробела, так же как при открытии блока. Каждая следующая метка возвращается на предыдущий уровень смещения, как при закрытии блока.
4.8.4.2 Сквозной проход комментируется
Внутри блока каждая группа операторов либо завершает досрочно switch (с помощью break, continue, return или выбросом исключения), либо помечается комментарием, чтобы обозначить, что выполнение кода будет или может быть продолжено в следующей группе. Достаточно любого комментария, передающего идею сквозного прохода (обычно // fall through). Такой комментарий не требуется в последней группе блока switch. Пример:
Обратите внимание, что комментарий ставится не после case 1, а лишь в конце группы операторов.
4.8.4.3 Всегда используйте default
Оператор switch должен содержать метку default, даже если в ней не присутствует код.
Исключение: блок switch для типа enum может не использовать default, если он содержит явные случаи, охватывающие все возможные значения этого типа. Это позволяет среде разработки или другим инструментам статического анализа выдавать предупреждение о том, что некоторые случаи не охвачены.
4.8.5 Аннотации
Аннотации, применяемые к классу, методу или конструктору, следуют непосредственно после блока документации. Каждая аннотация указывается на собственной строке (то есть по одной аннотации на строку). Эти разрывы строки не являются переносами строки (см. Раздел 4.5), поэтому уровень отступа не увеличивается. Пример:
Исключение: одиночная аннотация без параметров может отображаться вместе с первой строкой сигнатуры, например:
Аннотации, применяемые к полю, также появляются сразу после блока документации, но в этом случае несколько аннотаций (возможно, параметризованных) могут быть перечислены в одной строке, например:
Не существует особых правил для форматирования аннотаций к параметрам, локальным переменным или типам.
4.8.6 Комментарии
Этот раздел посвящен комментариям реализации. Javadoc рассматривается отдельно в Разделе 7.
Любому разрыву строки может предшествовать произвольное количество пробелов, за которым следует комментарий реализации. Такой комментарий делает строку непустой.
4.8.6.1 Стиль блочного комментария
Уровень отступа блочного комментария совпадает с окружающим кодом. Блочные комментарии могут быть как /* … */, так и // … Для многострочных комментариев вида /* … */ последующие строки должны начинаться с символа *, выравненного с символом * с предыдущей строки.
Комментарии не заключаются в прямоугольники, изображенные звездочками или другими символами.
При написании многострочных комментариев используйте стиль /* … */, если хотите, чтобы средства автоматического форматирования кода делали перенос строки при необходимости (в стиле параграфов). Большинство средств форматирования не могут делать этого с блоками однострочных комментариев // …
4.8.7 Модификаторы
Модификаторы класса и полей, если они присутствуют, отображаются в порядке, рекомендованном спецификацией языка Java:
4.8.8 Числовые литералы
Тип long использует прописную букву L, а не строчную (чтобы не перепутать с цифрой 1). Например, 300_000_000L вместо 300_000_000l.
5. Именование
5.1 Общие правила для всех идентификаторов
Идентификаторы используют только буквы и цифры ASCII и, в некоторых отмеченных ниже случаях, подчеркивания.
Таким образом, каждому действительному имени идентификатора соответствует регулярное выражение \w+ (буквенно-цифровой символ, встречающийся один или более раз).
Стилю данного руководства не соответствуют имена, использующие специальные суффиксы или префиксы, например: name_, mName, s_name или kName.
5.2 Правила для разных типов идентификаторов
5.2.1 Имена пакетов
Имена пакетов должны быть записаны в нижнем регистре, без использования camelCase или подчеркиваний.
Правильно: com.example.deepspace Неправильно: com.example.deepSpace или com.example.deep_space
5.2.2 Имена классов
Имена классов пишутся в стиле UpperCamelCase (с заглавной первой буквой).
Имена классов обычно являются существительными или словосочетаниями с существительными. Например, Character или ImmutableList.
Имена интерфейсов также могут быть существительными или словосочетаниями с существительными (например, List), но иногда могут быть и прилагательными или сочетаниями прилагательных (например, Readable).
Не существует конкретных правил или даже устоявшихся соглашений для именования типов аннотаций.
Тестовые классы носят имя, которое начинается с имени класса, который они тестируют, и заканчивается словом Test. Например, HashTest или HashIntegrationTest.
5.2.3 Имена методов
Имена методов пишутся в стиле lowerCamelCase.
Имена методов обычно являются глаголами или словосочетаниями с глаголами. Например, sendMessage или stop.
Подчеркивания могут присутствовать в именах тестовых методов JUnit для разделения логических компонентов в имени. При этом каждый компонент пишется в стиле lowerCamelCase. Типичным шаблоном является:
Не существует единственно верного пути в именовании тестовых методов.
5.2.4 Имена констант
Константы именуются в стиле CONSTANT_CASE: все буквы в верхнем регистре, каждое слово отделено от следующего подчеркиванием. Но что именно является константой?
Константы — это статические финальные поля, содержимое которых является неизменным, и методы, которые не имеют видимых побочных эффектов. Это относится к примитивам, String, неизменяемым типам и неизменяемым коллекциям неизменяемых типов. Если какое-либо наблюдаемое состояние объекта может измениться, он не является константой. Простого намерения никогда не изменять объект недостаточно.
Имена констант обычно являются существительными или словосочетаниями с существительными.
5.2.5 Имена не константных полей
Имена полей, не являющихся константами (статических или нет), пишутся в стиле lowerCamelCase.
Имена таких полей обычно являются существительными или словосочетаниями с существительными. Например, computedValues или index.
5.2.6 Имена параметров
Имена параметров пишутся в стиле lowerCamelCase.
В публичных методах следует избегать имен параметров, состоящих из одного символа.
5.2.7 Имена локальных переменных
Имена локальных переменных пишутся в стиле lowerCamelCase.
Даже будучи финальными и неизменяемыми, локальные переменные не считаются константами и не должны писаться в том же стиле, что и константы.
5.2.8 Имена переменных типа
Каждая переменная типа именуется согласно одному из двух стилей:
5.3 «Верблюжий» стиль (camelCase)
Иногда существует более одного способа преобразовать фразу на английском языке в «верблюжий» стиль, как например в случае с аббревиатурами или нетипичными выражениями вроде «IPv6» или «iOS».
Для повышения предсказуемости, данное руководство задает следующую (примерную) схему.
Начинаем с исходной формы имени:
1. Преобразуйте фразу в обычный ASCII и удалите все апострофы. Например, «Müller’s algorithm» можно преобразовать в «Muellers algorithm»
2. Разделите полученный результат на слова, отбрасывая пробелы и оставшиеся знаки пунктуации (обычно дефисы):
Обратите внимание, что регистр исходных слов почти полностью игнорируется.
Исходная форма
Правильно
Неправильно
«XML HTTP request»
XmlHttpRequest
XMLHTTPRequest
«new customer ID»
newCustomerId
newCustomerID
«inner stopwatch»
innerStopwatch
innerStopWatch
«supports IPv6 on iOS?»
supportsIpv6OnIos
supportsIPv6OnIOS
«YouTube importer»
YouTubeImporter YoutubeImporter*
*Допускается, но не рекомендуется.
Примечание: некоторые слова в английском языке используют дефис неоднозначно: например, оба слова «nonempty» и «non-empty» являются правильными, поэтому имена методов checkNonempty и checkNonEmpty также являются правильными.
6. Практика программирования
6.1 Используйте всегда аннотацию @Override
Метод помечается аннотацией @Override всякий раз, когда он действительно переопределяется. Это относится как к методу класса-потомка, переопределяющему метод класса-родителя, так и к методу интерфейса, переопределяющему метод супер-интерфейса.
Исключение: аннотация может быть опущена, если родительский метод помечен аннотацией @Deprecated.
6.2 Не игнорируйте пойманные исключения
Очень редко возникают ситуации, когда не нужно предпринимать ни каких действий в ответ на пойманное исключение (типичным решением является занесение в лог или, если это считается «невозможным», перебросить исключение как AssertionError).
Ниже приведен пример с поясняющим комментарием, когда действительно уместно не предпринимать никаких действий в блоке catch:
Исключение: в тестах пойманное исключение может быть проигнорировано и не сопровождено комментарием, если именем теста является expected или же, если имя начинается с expected. Ниже приводится очень распространенная идиома, показывающая, что тестируемый код генерирует исключение ожидаемого типа, поэтому здесь комментарии не нужны:
6.3 Для статических членов используйте имя класса
Обращаться к члену статического класса необходимо через имя класса, а не по ссылке на объект класса или по выражению, возвращающему этот объект:
6.4 Не используйте финализаторы
Крайней редко необходимо переопределить метод Object.finalize.
Не делайте этого. Если вам действительно это нужно, сначала прочитайте и очень тщательно осмыслите Effective Java Item 7, «Avoid Finalizers», а затем — не делайте этого.
7. Javadoc
7.1 Форматирование
7.1.1 Основная форма
Простое форматирование блоков Javadoc соответствует данному примеру:
Простая форма применима всегда. Однострочная форма может быть применена, когда весь блок Javadoc (включая маркеры комментариев) может поместиться на одной строке. Обратите внимание, что это применимо лишь тогда, когда в блоке нет таких тэгов, как @return.
7.1.2 Параграфы
непосредственно перед первым словом, без пробела после.
7.1.3 Блочные тэги
Все блочные тэги следуют в таком порядке: @param, @return, @throws, @deprecated, и эти четыре типа никогда не присутствуют с пустым описанием. Если тег блока не помещается на одной строке, строки продолжения имеют отступ в четыре (или более) пробела от @.
7.2 Итоговый фрагмент
Каждый блок Javadoc начинается с краткого итогового фрагмента. Этот фрагмент очень важен: это единственный текст, который присутствует в определенном контексте, таком как индексы классов и методов.
Этот фрагмент — словосочетание с существительным или глаголом, а не с полным предложением. Он не начинается с A <@code Foo>is a… или This method returns…, и не образует законченного утвердительного предложения, как например Save the record. Однако этот фрагмент пишется с заглавной буквы, и в нем проставляются знаки пунктуации, как если бы это было законченное предложение.
Подсказка: распространенной ошибкой является написание простого Javadoc в виде /** @return the customer ID */. Это неверно и должно быть исправлено на /** Returns the customer ID. */.
7.3 Когда применяется Javadoc
Javadoc присутствует по меньшей мере в каждом public классе и в каждом public и protected члене такого класса, за исключением некоторых случаев, описанных ниже. Дополнительный Javadoc может присутствовать, как это разъяснено в Разделе 7.3.4, Необязательный Javadoc.
7.3.1 Исключение: методы, описывающие себя
Javadoc опционален для простых и очевидных методов, таких как getFoo, в тех случаях, когда действительно нельзя сказать ничего более, чем «Возвращает foo».
Важно: неуместно ссылаться на это исключение, чтобы оправдать пропуск соответствующей информации, которую может потребоваться обычному читателю.
Например, для метода с названием getCanonicalName не опускайте документацию (с тем основанием, что имя метода говорит лишь /** Возвращает каноническое имя. */), если обычный человек, читающий код, может и не подозревать, что означает термин «каноническое имя»!
7.3.2 Исключение: переопределение
Javadoc не всегда сопровождает метод, который переопределяет метод из супер-класса (или супер-интерфейса).
7.3.4 Необязательный Javadoc
Прочие классы и члены сопровождаются Javadoc по необходимости или по желанию.
Всякий раз, когда комментарий реализации будет использоваться для определения общей цели или поведения класса или члена, этот комментарий записывается как Javadoc (с использованием /**).
Необязательный Javadoc не обязательно должен следовать правилам форматирования Разделов 7.1.2, 7.1.3 и 7.2, хотя это, конечно, рекомендуется.