When writing a program in any language, you should adhere to some agreement on the design code. A convention, or standard, describes where and how to put line breaks, what indents should be made for blocks of code, and so on.
Why do we need agreements on the design of the code?
If at first it seems that the design of the code according to the standard is not so important, then I will say the following: about 80% of the time spent working on the program is support. That is, 80% is spent on finding bugs, on minor fixes and adding new features. In other words, 80% of the time you have to dig into the existing code. And the program code of medium and large projects will almost certainly be served by not just one person, but at least a few.
Therefore, it is so important that each programmer individually adheres to one design standard adopted in this development team. If your “team” consists of only one person, then even in this case, you must adhere to the standards, because after some time you will have to go back to the old code, trying to remember how it works.
Compare two passages of the same code, decorated in different ways. One of them is designed anyhow, and the other (guess what :)) - using the "Java Coding Conventions" code design agreement. Which one is easier to understand?
public String toString () { int len = this.end - 0; char [] ss = new char [len]; for (int i = 0; i
public String toString () { int len = this.end; char [] ss = new char [len]; for (int i = 0; i
Common code design conventions
Almost every large organization or development group has its own code design standard. One of the standards proposed by Sun for programming in Java is "Java Code Conventions", following which, it turns out very compact, but at the same time perfectly readable code. Java Code Conventions are largely applicable to other languages, for example, PHP.
In the code for indenting, the Java Code Conventions allows the use of both spaces and tabs. However, practice shows that indentations with spaces are more “reliable” in the sense of code portability. For example, code formatted only with spaces can be transferred from one project to another without losing formatting, even if the tab size of a tab is set to different in the settings of different projects.
In many development environments, a tab character size of four spaces is configured by default. This, I am convinced, is fundamentally wrong. Historically, the tab character takes 8 spaces from the beginning of the line. When the editor instead of 4 spaces puts a tab in the file, then opening the same file with any other editor that displays the "standard" 8 characters on the tab, we get the dump of unformatted code.
It comes around when you have to make changes to the program not with your favorite editor in your favorite finely tuned IDE, but with some kind of Far or with a regular notebook, in the field.
There is a so-called "Hungarian notation" that prescribes to give names to variables and members of classes using prefixes that indicate the type of variable, for example:
int m_iCount; LPCTSTR m_lpszName;
The benefits of the Hungarian notation are questionable, since the types of variables can often change, especially with active development, and to introduce constructions like “m_lpszName” instead of “name” each time is a dubious pleasure.
Teamwork
In the case of team work on a project, whatever agreements on indents, line breaks and other nuances of code design are chosen, they should be stored in the project properties, if possible, so that using the version control system (SVN, GIT) these settings will automatically appear each developer.
In Eclipse, quite fine formatting settings can be set both at the Workspace level and in the project itself. In the case of collaboration, the settings should be done in the project.
Auto Format
Ideally, the code design standard should be provided by the development environment itself. If there are no external factors that impose any design features, then all settings can be configured in the IDE in which you work. Modern development environments are able to format the source code in accordance with the specified settings. This allows you not to bother with formatting, but give the IDE command to format the code itself. This can be done both for a small fragment, and for the entire file. IDE auto-formatting is a very useful feature that should be used.
Typically, the formatting of the source is called by right-clicking on the program text in the IDE, and then we select the item in the drop-down menu. For example, in NetBeans - Format.
When working as a team, the formatting settings should be accessible through the source control system to all team members, therefore, the auto formatting will give the same result.
***
Java code conventions
September 12, 1997
***
Copyright information
(c) 1997, Sun Microsystems, Inc. All rights reserved.
2550 Garcia Avenue, Mountain View, CA 94043-1100 USA
This document is copyrighted. No part of this document may be reproduced in any form or by any means without written permission from Sun and its licensors, if any.
The information described in this document may be protected by one or more US patents, foreign patents, or applications under development.
TRADE MARKS
Sun, Sun Microsystems, Sun Microelectronics, Sun logo, SunXTL, JavaSoft, JavaOS, JavaSoft logo, Java, HotJava Views, HotJJavaChips, picoJava, microJava, UltraJava, JDBC, Java Cup logo and Steam, "Write Once, Run Anywhere" and Solaris are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.
UNIX ® is a registered trademark in the United States and other countries, licensed exclusively through X / Open Company, Ltd.
Adobe ® is a registered trademark of Adobe Systems, Inc.
Netscape Navigator ™ is a trademark of Netscape Communications Corporation.
All other product names mentioned herein are the trademarks of their respective owners.
THIS DOCUMENT IS PROVIDED "AS IS" WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON CHARGE.
THIS DOCUMENT MAY CONTAIN TECHNICAL INACCURACIES OR TYPOGRAPHIC ERRORS. INFORMATION HEREIN HAS BEEN PERIODICALLY UPDATED; THESE CHANGES WILL BE INTRODUCED INTO THE FOLLOWING EDITIONS OF THE DOCUMENT. SUN MICROSYSTEMS, INC. MAY MAKE CORRECTIONS AND / OR CHANGES IN THE PRODUCT (AH) AND / OR THE PROGRAM (AH) DESCRIBED IN THIS DOCUMENT AT ANY TIME.
Available for recycling
***
1. Introduction
1.1. Why do we need agreement on the design code
1.2 Acknowledgments
2 Filenames
2.1 File Suffixes
2.2 Names of shared files
3 File Organization
3.1 Source Files
3.1.1 Header Comments
3.1.2 Packages and Imports
3.1.3 Declaring Classes and Interfaces
4. paragraph
4.1 Line Length
4.2 Line Breaks
5 Comment
5.1 Registration of implementation comments
5.1.1 Block comments
5.1.2 Single line comments
5.1.3 Comments at the end of the line (block)
5.1.4 Comments at the end of the line (single line)
5.2 Documentary Comments
6 Listings
6.1 Line Numbering
6.2 Accommodation
6.3 Initialization
6.4 Classes and Interfaces Declarations
7 Operators
7.1 Simple Operators
7.2 Compound Operators
7.3 Operator return
7.4 Conditional if..else statement
7.5. For operator
7.6 while statement
7.7 do-while
7.8 switch statement
7.9 try-catch statement
8 spaces
8.1 Blank lines
8.2 Empty Spaces
9 Naming Conventions
10 Programming Practice
10.1 Providing access to instances and class variables
10.2 Accessing Class Variables and Methods
10.3 Constants
10.4 Setting Variable Values
10.5 Other recommendations
10.5.1 Parentheses
10.5.2 Return Values
10.5.3 Expressions '?' before a conditional statement
10.5.4 Special Comments
11 Code Examples
11.1 Sources
***
Java code format conventions
1. Introduction
1.1. Why do we need agreement on the design code
Code conventions are important for programmers for a number of reasons:
• 80% of the time spent using the software component is spent on its maintenance.
• Rarely the program is maintained throughout its life by the first author.
• Code agreement improves the readability of the software, which allows engineers to understand the new code more quickly and in detail.
• If you supply your code as a product, you need to make sure that it is as well grouped and clean as any other product you create.
1.2. Acknowledgments
This document reflects the standards for writing Java code introduced in the Java Language Specification, from Sun Microsystems, Inc. Thanks to Peter King, Patrick Naughton, Mike DeMoney, Jonni Kanerva, Kathy Walrath, and Scott Hommel.
For adaptation, modification, or distribution of this document, please read our copyright notice at http://java.sun.com/docs/codeconv/html/Copyright.doc.html.
Comments on this document should be submitted in the feedback form at http://java.sun.com/docs/forms/sendusmail.html.
2. Filenames
This section lists commonly used file suffixes and names.
2.1. File extensions
JavaSoft uses the following file extensions:
File Type | Extension
-----------------------
Java source code | .java
Java bytecode | .class
2.2. Common File Names
Commonly used file names include:
File Name | Using
-----------------------
GNUmakefile | The preferred name for makefiles. We use gnumake to build our software.
README | The preferred file name that summarizes the contents of a specific directory.
3. File structure
The file consists of sections, which should be separated by empty lines and optional comments defining each section.
Files longer than 2000 lines are cumbersome and should be avoided.
For an example of a properly styled Java program, see “Java Source File Example” on page 19.
3.1. Java source files
Each Java source file contains one 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 must be the first class or interface in the file.
Java source files have the following structure:
* Opening comments (see “Opening Comments” on page 4)
* Package and import information; eg:
import java.applet.Applet;
import java.awt. *;
import java.net. *;
* Declaring classes and interfaces (see "Declaring Classes and Interfaces" on page 4)
3.1.1. Opening Comments
All source files must begin with a C-style comment that lists the programmer (s), date, copyright, and a brief description of the purpose of the program. For example:
/ *
* Class name
*
Version Information
*
* Copyright Notice
* /
3.1.2. Package and Import Information
The first non-commentary line in most Java sources is package information, followed by import information. For example:
package java.awt;
import java.awt.peer.CanvasPeer;
3.1.3 Declaring Classes and Interfaces
The table below describes the declaration of a part of a class or interface in the order they appear. See "Example Java source file" on page 19 for an example with comments.
| declaration of the class / interface | notes
-------------------------------------------------- ---------------------------------
1 | Comments on class / interface documentation (/**...*/) | See “Documentation Comments” on page 9 for information on what should be in this comment.
2 | Class or interface statements
3 | Comments on the implementation of the class / interface (/*...*/), if necessary | These comments should contain extended class / interface information that is not relevant to class / interface documentation comments.
4 | Static class variables | First public class variables, then protected, then batch (without an access specifier) and then private.
5 | Non static variables | First public, then protected, then package (without an access specifier) and then private.
6 | Constructors
7 | Methods | These methods should be grouped more by functionality than by scope or availability. For example, a private class method may be between two random public methods. The goal is to make reading and understanding the code easier.
Indentation
One indent must contain four spaces. The exact indent format (spaces or tabs) is not specified. Tabs should contain 8 spaces (not 4).
4.1 Line Length
Avoid strings longer than 80 characters, because they can be misinterpreted by many terminals and other devices.
Note: for the examples used in the documentation, the string length should be less - usually no more than 70 characters.
Line breaks
In cases where the expression is not included on one line, make the transition to another in accordance with these general principles:
* start a new line after comma
* start a new line after the operator
* go to a new line at a higher level in the code
* when part of the expression is transferred to a new line, start it at the same level as the beginning of the expression
* If the rules mentioned above lead to the fact that the code is hard to read or is too shifted to the right, then simply indent 8 spaces.
Some examples of line breaks for method calls:
function (longExpression1, longExpression2, longExpression3,
longExpression4, longExpression5);
var = function1 (longExpression1,
function2 (longExpression2,
longExpression3));
Below are examples of line breaks for arithmetic expressions. The first option is preferable, since the transfer is done after the expression in parentheses, that is, at a higher level.
longName1 = longName2 * (longName3 + longName4 - longName5)
+ 4 * longname6; // It is better
longName1 = longName2 * (longName3 + longName4
- longName5) + 4 * longname6; // Worse
The following are two examples of line breaks in a method definition. The first uses the agreement. In the second, the use of conventions would have resulted in the second and third lines being too shifted to the right, so only an indent of 8 spaces is used.
// AGREEMENT ON ACCESSES
someMethod (int anArg, Object anotherArg, String yetAnotherArg,
Object andStillAnother) {
...
}
// RELEASE IN 8 CHARACTERS TO AVOID DEEP INVESTMENT
private static synchronized horkingLongMethodName (int anArg,
Object anotherArg, String yetAnotherArg,
Object andStillAnother) {
...
}
String formatting for an if expression should use an 8-character indent, because using the standard (4-character) makes it difficult to view the body of the expression. For example:
// DO NOT TAKE IT OUT
if ((condition1 && condition2)
|| (condition3 && condition4)
||! (condition5 && condition6)) {// POOR DESIGN
doSomethingAboutIt (); // ALLOWS TO EASILY MISS THIS LINE
}
// IT IS BETTER TO DO THIS
if ((condition1 & amp; & amp; condition2)
|| (condition3 && condition4)
||! (condition5 && condition6)) {
doSomethingAboutIt ();
}
// OR THIS IS
if ((condition1 && condition2) || (condition3 && condition4)
||! (condition5 && condition6)) {
doSomethingAboutIt ();
}
The following are three acceptable ways to format ternary expressions:
alpha = (aLongBooleanExpression)? beta: gamma;
alpha = (aLongBooleanExpression)? beta
: gamma;
alpha = (aLongBooleanExpression)
? beta
: gamma;
5 Comments
Java programs can have two kinds of comments: implementation comments and documentation comments. Implementation comments, similar to comments in C ++, are limited to /*...*/ and //. Documentation comments (known as “doc comments”) are found only in Java and are limited to / ** ... * /. Based on the documentation comments using the javadoc utility can be created documentation files in HTML format.
Implementation Comments are the means for commenting on the code or implementation features. Documentation comments are intended to describe the characteristics of the implementation-independent code so that in the future they can be read by the developer, who will not necessarily have the source code at hand.
Comments should be used to give a brief overview of the code and provide additional information that cannot be easily obtained from the code directly. Comments should contain only information that relates to the reading and understanding of the program. For example, information about how the corresponding package is built, or about the directory in which it is located, should not be included as a comment.
Explanation of non-trivial or non-obvious design decisions is allowed, but duplication of the information that is present in the code (and is clear from it) should be avoided. Excessive comments quickly become obsolete. In general, avoid any comments that are likely to become obsolete with code development.
Note: The frequency of comments sometimes reflects poor code quality. If you feel that you need to add more comments, think, probably you need to rewrite such code to make it more understandable.
Comments should not be enclosed in large blocks, with asterisks or other characters.
Comments should never include utility characters such as carriage returns and backspace.
5.1 Execution comments
A program may contain such styles of implementation comments as: “block”, “single line”, or “comment at the end of the line”
5.1.1 Block Comment
Block comments are used to describe files, methods, data structures, and algorithms. A block comment must be present at the beginning of each file and before each method. They can also be used in other places: for example, within methods. A block comment inside a function or method must be aligned with the level of the commented code.
To separate from the rest of the code, the block comment must be preceded by an empty line. Each line of the block comment, except the first, must begin with an asterisk ("*").
/ *
* This is a block comment
* /
Block comment starts with "/ *". The appearance of the comment body should not be changed. Example:
/ *
* This is a block comment with very specific
* design that does not use indents
*
* one
* two
* три
* /
Замечание: Если вы используете отступы, то и блочный комментарий не используйте или пойдите на уступки чтобы другие могли прибегнуть к идентации вашего кода.
См. также "Документирующий комментарий" на стр. 9.
5.1.2 Однострочные комментарии
Короткий комментарий можно разместить на одной строке, выровненой по уровню следующего за ним кодом. Если комментарий не умещается на одной строке, его нужно записать как блочный комментарий(смотри раздел 5.1.1). Перед однострочным комментарием стоит оставить пустую строку. Вот пример кода с однострочным комментарием (см. также "Документирующие комментарии" на стр. 9):
if (условие) {
/* Обработка условия */
...
}
5.1.3 Комментарии в конце строки (блочные)
Very short comments can be on the same line as the commented code, but should be indented from it. If there are more than one such comments in the code fragment, they should be aligned with the same level. Avoid commenting, as in assembler, at the end of each line of executable code.
Here is an example of a code with a block comment at the end of a line (see also “Documenting comments” on page 9)
return TRUE; /* an exception */
return isprime (a); / * only for odd a * /
5.1.4 Comments at the end of the line (single line)
"//" is a sign indicating the beginning of a single-line comment in the flesh to the end of the line. It can occupy the entire line or only part of it. You should not use a single-line comment for multi-line text; however, you can comment out part of the code. An example of all three styles:
// Do a double flip
return false; // Explain why here.
// // Do a triple coup.
5.2 Documentary Comments
Documentation comments are used to describe classes, interfaces, constructors, methods, and fields. Each documenting comment is /**...*/ and refers only to one particular API element. This comment should precede the element for which the description is made:
expression ;
} else if (condition) {
expression ;
}
expression;
for (initialization; condition; update) {
expression;
}
for (initialization; condition; update);
while (condition) {
expression;
}
while (condition);
do {
expression;
} while (condition);
switch (condition) {
case ABC:
expression;
case def:
expression;
break;
case XYZ:
expression;
break;
default:
expression;
break;
}
try {
expression;
} catch (ExceptionClass e) {
Comments
To leave a comment
Software and information systems development
Terms: Software and information systems development