Code Style: Difference between revisions

From GT New Horizons
Content added Content deleted
m (WIP)
m (WIP)
Line 485: Line 485:
while (condition)
while (condition)
one_line_statement;
one_line_statement;
</pre>

An empty while statement should have the following form:

<pre>
while (condition);
</pre>
</pre>

Revision as of 13:26, 16 October 2022

This page describes the suggested Java Code Style for the development of GTNH.

Use automatic formatting provided by IntelliJ IDEA. It is available via a shortcut: Ctrl+Alt+L on Windows, L on macOS, or from the main menu: "Code > Reformat Code".

Introduction

Why Have Code Conventions

Code conventions are important to programmers for a number of reasons:

  • For a piece of software, the vast majority of lifetime-cost goes to maintenance.
  • Code is read more often than it's written.
  • We have many developers working on the modpack. Consistent code style makes shared ownership easier.
  • Code conventions improve the readability, allowing engineers to understand new code quicker and better.

Acknowledgements

This is intended to be a living document to be updated as the needs of the team change and as new language features are introduced.

The intention of this guide is to provide a set of conventions that encourage good code. It is the distillation of many combined man-years of software engineering and Java development experience.

While some suggestions are more strict than others, you should always practice good judgement.

If following the guide causes unnecessary hoop-jumping or otherwise less-readable code, readability trumps the guide. However, if the more 'readable' variant comes with perils or pitfalls, readability may be sacrificed.

In general, much of our style and conventions mirror the Code Conventions for the Java Programming Language. Other good references are Google's Java Style Guide and Twitter's Java Style Guide.

Recommended Reading

Good books for code style and conventions:

File Organization

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.

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:

  • Beginning comments
  • Package and Import statements
  • Class and interface declaration(s)

Beginning Comments

Classes/Interfaces should be named well and in packages that provide context so a comment at the beginning of files giving a description of the class/interface is not needed.

Note: Do not use IDEA’s standard file comment’s templates. Your files should not mention IDEA (or other IDE). To set up file header, go to File > Settings > Editor > File and Code Templates | Includes | File Header.

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:

package java.awt;

import java.awt.peer.CanvasPeer;

Imports should have separate section for java and javax, and mixed static (see below) and regular imports.

Static imports are not used with the following exceptions:

  • Math.* if it's clear that numeric value passed as a parameter.
  • java.util.stream.Collectors

In tests, utility classes with assertion methods:

  • org.junit.Assert
  • org.mockito.Mockito.* and org.mockito.ArgumentMatchers.*
  • org.hamcrest.Matchers, CoreMatchers, Matcher, MatcherAssert and alike
  • org.junit.jupiter.api.Assertions and alike
  • org.assertj.core.api.Assertions and alike

As a result, the import part would look as follows:

package

import all other regular or static imports

import javax.*
import java.*

Class and Interface Declarations

The following table describes the parts of a class or interface declaration, in the order that they should appear.

Part of Class/Interface Declaration Notes
1 Class/interface documentation comment (/**...*/) Optional
2 class or interface statement
3 Class/interface implementation comment (/*...*/) Optional. This comment should contain any class-wide or interface-wide information that wasn't appropriate for the class/interface documentation comment.
4 Class static variables First the public class variables, then the protected, then package level (no access modifier), and then the private.
5 Instance variables First public, then protected, then package level (no access modifier), and then private.
6 Constructors
7 Methods These methods should be grouped by functionality rather than by scope or accessibility. For example, a private

class method can be in between two public instance methods. The goal is to make reading and understanding the code easier.

Indentation

Four spaces should be used as the unit of indentation. Indentation should be achieved with the Tab symbol. The IDE should be set to force Tab to move cursor right 4 positions.

GTNH code style overrides the Sun style by stating Tab characters - Sun leaves it unspecified.

Line Length

Avoid lines longer than 120 characters, since they're not handled well by many terminals and tools.

GTNH Code Style overrides the Sun line length of 80 characters.

Wrapping Lines

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.
  • Prefer higher-level breaks to lower-level breaks.
  • Align the new line with the beginning of the expression at the same level on the previous line.
  • After that, the break of the long code line to the to the next line is indented with the single (and not double) Tab. In other words, with 4 spaces.
  • The continuation on the third line is indented with another single Tab.

Here are some examples of breaking method calls:

someMethod(longExpression1, longExpression2, longExpression3,
    longExpression4, longExpression5);

var = someMethod1(tookTheFirstLine,
    someMethod2(tookTheSecondLine,
        longExpression3));

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.

longName1 = longName2 * (longName3 + longName4 - longName5)
    + 4 * longname6; // PREFER

longName1 = longName2 * (longName3 + longName4
    - longName5) + 4 * longname6; // AVOID

When a method parameter list or a condition in an if or while statement is indented, move the opening brace to the next line.

private static synchronized veryLongMethodName(int anArg,
    Object anotherArg, String andAnotherOne,
    Object andYetAnotherOne)
{
    methodBody();
}

if ((condition1 && condition2)
    || (condition3 && condition4)
    ||!(condition5 && condition6))
{
    doSomethingAboutIt();
}

Comments

Java programs can have two kinds of comments: implementation comments and documentation (doc) comments.

Implementation comments are meant 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.

Discussion of nontrivial or non-obvious 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.

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.

Code should not be commented out: delete the code instead. It will be available from the Git history if it is needed in the future.

Implementation Comment Formats

Programs can have four styles of implementation comments: block, single-line, trailing, and end-of-line.

Block Comments

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 to set it apart from the rest of the code.

codeGoesHere();

/*
 * Here is a block comment.
 */
moreCode();
Single-Line Comments

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. Here's an example of a single-line comment:

if (condition) {
    /* Handle the condition. */
    ifCode();
}
Trailing 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 chunk of code, they should all be indented to the same tab setting. Here's an example of a trailing comment:

if (a == 2) {
    return TRUE;              /* special case */
} else {
    return isPrime(a);        /* works only for odd a */
}
End-Of-Line Comments

The // comment delimiter can comment out a complete line or only a partial line. It shouldn't be used on consecutive multiple lines for text comments. Usage examples:

if (foo > 1) {
    // Do a double-flip.
    return bar.performDoubleFlip();
} else {
    return false;                    // Explain why here.
}

Documentation Comments

For further details, see How to Write Doc Comments for Javadoc which includes information on the doc comment tags @return, @param, and @see.

Doc comments describe Java classes, interfaces, constructors, methods, and fields. Each doc comment is set inside the comment delimiters /**...*/, with one comment per class, interface, or member. This comment should appear just before the declaration:

/**
 * The ShinyBlock class provides the functionality ...
 */
public class ShinyBlock { ...

Note that top-level classes and interfaces are not indented, but their members are. The first line of doc comment /** for classes and interfaces is not indented, but 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.

Authorship

Usage of @author tag is neither required, nor prohibited. Keep in mind that version control system already has the always up-to-date information about the people who worked on a given piece of code.

Deprecation

If you the @deprecated javadoc annotation, you must provide a comment, pointing the readers of code to the solution they should be using instead. See also an official guide on deprecation. Please note that the @Deprecated annotation should always be present if the @deprecated javadoc tag is present, and vice-versa.

Declarations

Number Per Line

One declaration per line is recommended since it encourages commenting.

int level; // indentation level
int size;  // size of table

The example above is preferred over the one below:

int level, size;

Do not put different types on the same line. Example:

int foo, fooarray[]; //WRONG!

Note: The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs:

int     level;        // indentation level
int     size;         // size of table
Object  currentEntry; // currently selected table entry

Initialization

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.

Placement

Put declarations only at the beginning of blocks. A block is any code surrounded by curly braces "{" and "}". Don't wait to declare variables until their first use -- it can confuse the unwary programmer and hamper code portability within the scope.

void myMethod() {
    int int1 = 0;      // beginning of method block

    if (condition) {
        int int2 = 0;  // beginning of "if" block
        ...
    }
}

The one exception to the rule is indexes of for loops, which in Java can be declared in the for statement:

for (int i = 0; i < maxLoops; i++) { ... }

Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:

int count;
...
myMethod() {
    if (condition) {
        int count = 0;
        ...
    }
    ...
}

// AVOID!

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.
  • Open curly braces stay on the same line when statement fits there, otherwise moved to a separate line.
  • Closing brace "}" starts a line by itself indented to match its corresponding opening statement, except when it is a null statement -- then the "}" should appear immediately after the "{".
  • Methods are separated by a blank line.
public void doSomething(int value) {
    ...
}

public Integer longMethodNameExample(LongTypeNameForParameter longVariableNameParameter,
    double parameterTwo)
{
    ....
}

Statements

Simple Statements

Each line should contain at most one statement. For example:

argv++;          // Correct
argc--;          // Correct
argv++; argc--;  // AVOID!

Compound Statements

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.
  • Open curly braces stay on the same line when statement fits there, otherwise moved to the separate line; the closing brace should begin a line and be indented to the same level as the beginning of the compound statement.

GTNH style overrides the Sun style which states: "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."

return Statements

A return statement with a value should not use parentheses unless they make the return value more obvious in some way. For example:

return;
return myDisk.size();
return (size ? size : defaultSize);

if, if-else, if else-if else Statements

The if code block should always be enclosed by curly braces. For simple single-line statements without else/else-if, the curly braces can be omitted.

if (shortCondition)
    oneLineStatement;

if (condition) {
    statement1;
} else {
    statement2;
}

if (condition1) {
    statement1;
} else if (condition2) {
    statement2;
} else {
    statement3;
}

When conditions or code block spreads several lines then the braces are required even when block consists of the single statement.

if (longVariableName == anotherLongVariableName
    && anotherCondition)
{
    oneLineStatement;
}

if (shortCondition) {
    multiple =
        line.statement();
}

if (shortCondition) {
    // comment
    line.statement();
}

if (shortCondition1) {
    if (shortCondition2)
        oneLineStatement;
}

Simple statements -- a single-line condition, single-line body and no else statement -- may omit the curly braces.

if (shortCondition)
    oneLineStatement;

for Statements

The for code block should always be enclosed by curly braces. For simple single-line loops, the curly braces may be omitted.

for (initialization; condition; update) {
    statementOne;
    statementN;
}

for (initialization; aReallyLongCondition;
    updateStatement)
{
    statement;
}

Simple, single line body may omit curly braces:

for (initialization; condition; update)
    aSimpleStatement;

An empty for statement -- one in which all the work is done in the initialization, condition, and update clauses -- should have the following form:

for (initialization; condition; update);

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.

while Statements

The while code block should always be enclosed by curly braces. For simple single line condition and statement, curly braces may be omitted.

while (condition) {
    multiLineStatement(
        argument1, argument2);
}

while (condition1
    && condition2)
{
    single_line_statement;
}

Simple, single line body may omit curly braces:

while (condition)
    one_line_statement;

An empty while statement should have the following form:

while (condition);