Code Style

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

Introduction
Code conventions are important 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 developers to understand new code quicker.

This page 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 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.

Good books for code style and conventions:


 * Clean Code by Robert Martin,
 * Effective Java by Joshua Bloch.

Spotless
GTNH uses Spotless to check line wrapping, spacing, and indentation.

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 interface or class which goes first in the file. When a private class is associated with a public class, you can put them in the same source file as the public one.

Java source files have the following ordering:
 * 1) Beginning comments
 * 2) Package and Import statements
 * 3) Class and interface declaration(s)

Beginning Comments
Classes/Interfaces should be named well and in packages that provide context, so there is no need to explain where it belongs in the starting comment.

Package and Import Statements
The first non-comment line of most Java source files is a package statement. After that, import statements can follow. They are ordered by Spotless.

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

Comments
Most of the time, code should not be commented out - delete it instead. If it's needed again, it will be available from the Git history.

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

Doc comments are meant to describe the specification of the code, from an implementation-free perspective. They are meant to be understood by the developers who might not 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 clearly understood 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.

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. 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;

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.

if (condition) { /* Handle the condition. */   ifCode; }

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.

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

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

Documentation Comments
Every class and nontrivial public method that you write should contain a Javadoc comment with at least one sentence describing what the class or method does. This sentence should start with a third person descriptive verb.

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:

/** * Does this and that ... */ public class ShinyBlock { ...

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  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  annotation should always be present if the   javadoc tag is present, and vice-versa.

Number Per Line
Multiple declarations per line can be the best course of action only of the variables are strongly connected. For instance, if they are 3D coordinates: int x, y, z;

Do not put different types on the same line. Example: int foo, fooarray[]; // AVOID!

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 the 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  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!

Statements
Compound statements are statements that contain lists of statements enclosed in braces. 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  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, for, while Statements
The  code blocks should always be enclosed by curly braces. For simple single-line statements without, the curly braces can be omitted.

switch Statements
A  expression can have either of the two forms:

In new code: switch (condition) { case ABC, DEF, KLM -> { statements; }   case XYZ -> { statements; }   default -> { statements; } }

In legacy code: switch (condition) { case ABC: statements; /* falls through */ case DEF: statements; break; case KLM: case XYZ: statements; break; default: statements; break; }

Do not write unnecessary  and   when they can be avoided.

Every time a case has 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. Comment can be left off if there are no statements in the case that falls through.

GTNH Style overrides Sun's to not require break's or default when avoidable. The Sun guide states: "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."

Naming
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.

Providing Access to Instance and Class Variables
Don't make any instance or class variable  without good reason. Often instance variables are set or obtained as a side effect of method calls instead of being accessed directly.

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:

classMethod;         // OK AClass.classMethod;   // OK anObject.classMethod; // AVOID!

Constants
Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a for loop as counter values. Well-named constants should be used instead.

For example, instead of, the following is advised: int CONSTANT_NAME = 16281;

methodName(CONSTANT_EXPLANATION);

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:

if (c++ = d++) {        // AVOID! (Java disallows) ... } // should be written as if (c = d++) != 0) {   ... }

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 a = b + c; d = a + r;

Deprecation
When using annotation @Deprecated, you must provide a comment referencing the solution that should be used instead. The @Deprecated annotation should always be present if the @deprecated javadoc tag is present, and vice-versa.

/** * @deprecated use {@link DBHelper#update(java.lang.String, java.util.Map)} */ @Deprecated(forRemoval = true) public int insert(String request, Map params) { // }

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.

if ((a == b) && (c == d)) // OK if (a == b && c == d)    // AVOID!

Returning Values
Try to make the structure of your program match the intent. Example:

if (booleanExpression) { return true; } else { return false; } // should instead be written as return booleanExpression;

Similarly,

if (condition) { return x; } return y; //should be written as return (condition ? x : y);

Ternary Operator
If an expression containing a binary operator appears before the ? in the ternary ?: operator, it should be parenthesized. Example:

(x >= 0) ? x : -x;

Here are three acceptable ways to format ternary expressions:

// Single line alpha = (aLongBooleanExpression) ? beta : gamma;

// 2 lines with values lined up alpha = (aLongBooleanExpression) ? beta : gamma; //Multi-line with values lined up under condition alpha = (aLongBooleanExpression) ? beta : gamma;

Special Comments
Use the  in a comment to flag something that is bogus but works.

Use  to flag something that is bogus and broken.

stream API
Each  etc. method call should be placed on a new line.

collection.stream .filter(...) .forEach(...);

lambda Expressions
The simplest presentation should be used for lambda expressions:

.forEach(item -> System.out.println(item)); // not correct .forEach(System.out::println);             // correct

.forEach(i -> {                            // not correct i.doSomething; }); .forEach(i -> i.doSomething);            // correct

Inner Classes
The following rule is applied to the inner classes
 * 1) All inner classes should be placed in the end of the file by default
 * 2) The exception of the rule one could be used when:
 * 3) Inner class definition does not exceed 30 lines of code and
 * 4) The definitions of the methods that call inner class immediately follow after the inner class definition and take not more than 60 lines altogether.

Methods
The methods should be formatted in the following way: 1. When method declaration fits in 120 characters it should be written in single line:

public static String concat(@FunctionParameterName("value1")Any s1, @FunctionParameterName("value2")Any s2) { return s1.getValue + s2.getValue; }

2. When method is longer it should spread multiple lines with each line is no longer 120 characters. Line breaks should made after the coma or between annotations. It is recommended to minimize the number of lines by making lines as long as possible.

public static int countTradingDays(CoreApi core, @FunctionParameterName("fromDate")int fromDate,   @FunctionParameterName("toDate")int toDate) {   ... }