Что такое java code conventions

Рекомендации к стилю кода

Правила языка Java

Правила Java библиотек

Существуют соглашения, по поводу использования 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 символов, так как люди редко на них смотрят. Также это упрощает написание инструментов.

Сокращения в именах

Рассматривайте сокращения и аббревиатуры как слова. Имена более удобочитаемы:

ХорошоПлохо
XmlHttpRequestXMLHTTPRequest
getCustomerIdgetCustomerID

Этот стиль также применяется, когда сокращение и аббревиатура — это полное имя:

ХорошоПлохо
class Htmlclass HTML
String url;String URL;
long id;long ID;

Стиль TODO

Используйте комментарии TODO для кода, который является временным, краткосрочным, или хорошим, но не идеальным. Комментарий должен включать в себя «TODO:», например:

Если ваш комментарий имеет вид «В будущем сделать что-то», то убедитесь, что он включает в себя конкретную дату (1 января 2011 года), или конкретное событие «Удалить после выхода версии 2.1».

Согласованность

Если вы изменяете код, то потратьте минуту на то, чтобы посмотреть на код вокруг вас и определить его стиль. Если в нем используются пробелы, то и вам следует их использовать. Если комментарии содержат небольшой набор звездочек, то и вам следует их использовать.

Весь смысл рекомендаций к стилю кода в создании общей лексики, чтобы люди концентрировались на том, что они говорят, вместо того как они говорят. Мы представляем глобальные правила стиля, чтобы люди знали эту лексику. Но локальный стиль также важен. Если код, который вы добавляете в файл выглядит резко отличным от того, что был, то это выбросит будущего читателя из его ритма и будет мешать ему понимать структуру. Старайтесь избегать этого.

Источник

Java Code Style: как правильно оформлять код Java

Статья об именах переменных, классов и методов, скобках, комментариях, форматировании кода и других правилах хорошего тона, принятых в языке Javа.

Что такое java code conventions. Смотреть фото Что такое java code conventions. Смотреть картинку Что такое java code conventions. Картинка про Что такое java code conventions. Фото Что такое java code conventions

Что такое java code conventions. Смотреть фото Что такое java code conventions. Смотреть картинку Что такое java code conventions. Картинка про Что такое java code conventions. Фото Что такое java code conventions

В языке Java, как и во многих других языках программирования, есть неофициальные, но принятые сообществом разработчиков соглашения по оформлению кода. Давайте попробуем разобраться, что это такое, как работает и почему важно.

Зачем нужен единый стиль кода

Java Code Style — это рекомендации и соглашения о стиле кода, собранные вместе. Например:

Регламентируется множество вещей, связанных с оформлением исходного текста программ, и приводятся требования, которые необходимо учитывать. Почему возникли эти стандарты?

Причины, по которым разработчики пришли к таким соглашениям, логичны и просты:

Использование общепринятых соглашений по оформлению позволяет сделать код более аккуратным, избежать ошибок, связанных с разными стилями написания у людей, работающих над одним проектом.

Что такое java code conventions. Смотреть фото Что такое java code conventions. Смотреть картинку Что такое java code conventions. Картинка про Что такое java code conventions. Фото Что такое java code conventions

Преподаватель Skillbox. Пишет про Java, учит Go. Помнит рассвет PHP и как «грабить корованы».

Форматирование на практике

Стиль не играет роли для компьютера, но важен для чтения кода человеком. Наше зрение устроено так, что сперва получает и анализирует образы, а только затем мы вдаёмся в детали. А если блоки исходного текста унифицированы, разработчик понимает, что перед ним за конструкция, даже не вникая в сам код.

Источник

Что такое java code conventions

Java Code Conventions

Why Have Code Conventions?

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 TypeRules of NamingExamples
PackagesThe 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.

ClassesClass 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;
InterfacesInterface names should be capitalized like class names.interface RasterDelegate; interface Storing;
MethodsMethods 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;
ConstantsThe 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:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *