Code Style: Difference between revisions

From GT New Horizons
Content added Content deleted
m (Move the Wrapping Lines section to the end of the doc, so it is available just in case.)
(Undo revision 10352 by Alastor's Game (talk))
 
(59 intermediate revisions by 3 users not shown)
Line 1: Line 1:
[[Category:Dev]]
This page describes the suggested Java Code Style for the development of GTNH.
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: [https://resources.jetbrains.com/storage/products/intellij-idea/docs/IntelliJIDEA_ReferenceCard.pdf Ctrl+Alt+L on Windows, L on macOS], or from the main menu: "Code >
Reformat Code".


== Introduction ==
== Introduction ==
Code conventions are important for a number of reasons:
=== 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.
* For a piece of software, the vast majority of lifetime-cost goes to maintenance.
* Code is read more often than it's written.
* Code is read more often than it's written.
* We have many developers working on the modpack. Consistent code style makes shared ownership easier.
* We have many developers working on the modpack. Consistent code style makes the development easier.
* Code conventions improve the readability, allowing engineers to understand new code quicker and better.
* Code conventions improve the readability, allowing developers to understand Pull Requests quicker.


The purpose of this Code Style is to provide a set of conventions that encourage good code.
=== 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.


Always practice good judgement. If following the guide causes unnecessary hoop-jumping or less-readable code, then readability trumps the guide. However, if the more "readable" variant comes with perils or pitfalls, then readability may be sacrificed.
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.


In general, much of this Code Style is a summary of the [https://www.oracle.com/java/technologies/javase/codeconventions-contents.html Code Conventions for the Java Programming Language]. Other good references are [https://google.github.io/styleguide/javaguide.html Google's Java Style Guide] and [https://github.com/twitter-archive/commons/blob/master/src/java/com/twitter/common/styleguide.md Twitter's Java Style Guide].
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 [https://www.oracle.com/java/technologies/javase/codeconventions-contents.html Code Conventions for the Java Programming Language]. Other good references are [https://google.github.io/styleguide/javaguide.html Google's Java Style Guide] and [https://github.com/twitter-archive/commons/blob/master/src/java/com/twitter/common/styleguide.md Twitter's Java Style Guide].

=== Recommended Reading ===
Good books for code style and conventions:
Good books for code style and conventions:


Line 29: Line 20:
* [https://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683 Effective Java] by Joshua Bloch.
* [https://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683 Effective Java] by Joshua Bloch.


=== File Organization ===
== Spotless ==
GTNH uses [https://github.com/diffplug/spotless Spotless] to check line wrapping, spacing, and indentation.
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 ====
== File Organization ==
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:
* 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:
<pre>
package java.awt;

import java.awt.peer.CanvasPeer;
</pre>

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:
* <code>Math.*</code> if it's clear that numeric value passed as a parameter.
* <code>java.util.stream.Collectors</code>

In tests, utility classes with assertion methods:
* <code>org.junit.Assert</code>
* <code>org.mockito.Mockito.*</code> and <code>org.mockito.ArgumentMatchers.*</code>
* <code>org.hamcrest.Matchers, CoreMatchers, Matcher, MatcherAssert</code> and alike
* <code>org.junit.jupiter.api.Assertions</code> and alike
* <code>org.assertj.core.api.Assertions</code> and alike

As a result, the import part would look as follows:
<pre>
package

import all other regular or static imports

import javax.*
import java.*
</pre>


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


Line 89: Line 38:
| 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.
| 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 <code>static</code> variables || First the <code>public</code> class variables, then the <code>protected</code>, then package level (no access modifier), and then the <code>private</code>.
| 4 || Class <code>static</code> variables || First <code>public</code> class variables, then <code>protected</code>, then package level (no access modifier), and then <code>private</code>.
|-
|-
| 5 || Instance variables || First <code>public</code>, then <code>protected</code>, then package level (no access modifier), and then <code>private</code>.
| 5 || Instance variables || First <code>public</code>, then <code>protected</code>, then package level (no access modifier), and then <code>private</code>.
Line 95: Line 44:
| 6 || Constructors ||
| 6 || Constructors ||
|-
|-
| 7 || Methods || These methods should be grouped by functionality rather than by scope or accessibility. For example, a private
| 7 || Methods || The 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.
class method can be in between two public instance methods. The goal is to make reading and understanding the code easier.
|}
|}


=== Indentation ===
== Comments ==
* Usually, code should not be commented out – delete it instead. If the code needed again, it will be available in the Git history.
Four spaces should be used as the unit of indentation.
* 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 of asterisks or other characters.


==== Line Length ====
==== Comment Styles ====
A single-line comment can use a double-slash notation:
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.

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

<pre>
codeGoesHere();

/*
* Here is a block comment.
*/
moreCode();
</pre>

===== 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:

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

===== 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:

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

===== End-Of-Line Comments =====
The <code>//</code> 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:
<pre>
<pre>
if (foo > 1) {
if (foo > 1) {
// Do a double-flip.
// Do a double-flip.
return bar.performDoubleFlip();
return bar.performDoubleFlip();
} else {
return false; // Explain why here.
}
}
</pre>
</pre>


If the comment spans multiple lines, then convert it to a block-comment:
==== Documentation Comments ====
<pre>
For further details, see [https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html How to Write Doc Comments for Javadoc] which includes information on the doc comment tags @return, @param, and @see.
codeGoesHere();


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

<pre>
/**
* The ShinyBlock class provides the functionality ...
*/
*/
moreCode();
public class ShinyBlock { ...
</pre>
</pre>


==== Authorship ====
Note that top-level classes and interfaces are not indented, but their members are.
The first line of doc comment <code>/**</code> 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.
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.
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 <code>@deprecated</code> javadoc annotation, you must provide a comment, pointing the readers of code to the solution they should be using instead.
See also an official [https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html#@deprecated guide] on deprecation.
Please note that the <code>@Deprecated</code> annotation should always be present if the <code>@deprecated</code> javadoc tag is present, and vice-versa.


== Declarations ==
== Declarations ==
=== Number Per Line ===
==== 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:
One declaration per line is recommended since it encourages commenting.
<pre>
<pre>
int x, y, z;
int level; // indentation level
int size; // size of table
</pre>

The example above is preferred over the one below:
<pre>
int level, size;
</pre>
</pre>


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

Note: The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs:
<pre>
int level; // indentation level
int size; // size of table
Object currentEntry; // currently selected table entry
</pre>
</pre>


=== Initialization ===
==== Initialization ====
Try to initialize local variables where they're declared.
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.
The only reason not to initialize a variable where it's declared is if the initial value depends on some computation occurring first.


=== Placement ===
==== Placement ====
Put declarations only at the beginning of blocks. A block is any code surrounded by curly braces "{" and "}".
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.
Don't wait to declare variables until the first use -- it can confuse the unwary programmer and hamper code portability within the scope.
<pre>
<pre>
void myMethod() {
void myMethod() {
Line 260: Line 104:
...
...
}
}
}
</pre>

The one exception to the rule is indexes of for loops, which in Java can be declared in the <code>for</code> statement:
<pre>
for (int i = 0; i < maxLoops; i++) { ... }
</pre>

Avoid local declarations that hide declarations at higher levels.
For example, do not declare the same variable name in an inner block:
<pre>
int count;
...
myMethod() {
if (condition) {
int count = 0;
...
}
...
}

// AVOID!
</pre>

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

<pre>
public void doSomething(int value) {
...
}

public Integer longMethodNameExample(LongTypeNameForParameter longVariableNameParameter,
double parameterTwo)
{
....
}
}
</pre>
</pre>


== Statements ==
== Statements ==
=== Simple Statements ===
==== switch Statements ====
It is suggested to use the following form:
Each line should contain at most one statement. For example:

<pre>
argv++; // Correct
argc--; // Correct
argv++; argc--; // AVOID!
</pre>

=== Compound Statements ===
Compound statements are statements that contain lists of statements enclosed in braces <code>{ statements; }</code>.
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 <code>return</code> statement with a value should not use parentheses unless they make the return value more obvious in some way. For example:

<pre>
return;
return myDisk.size();
return (size ? size : defaultSize);
</pre>

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

<pre>
if (shortCondition)
oneLineStatement;

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

if (condition1) {
statement1;
} else if (condition2) {
statement2;
} else {
statement3;
}
</pre>

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

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

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

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

if (shortCondition1) {
if (shortCondition2)
oneLineStatement;
}
</pre>

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

<pre>
if (shortCondition)
oneLineStatement;
</pre>

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

<pre>
for (initialization; condition; update) {
statementOne;
statementN;
}

for (initialization; aReallyLongCondition;
updateStatement)
{
statement;
}
</pre>

Simple, single line body may omit curly braces:

<pre>
for (initialization; condition; update)
aSimpleStatement;
</pre>

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

<pre>
for (initialization; condition; update);
</pre>

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 <code>for</code> loop for the initialization clause or at the end of the loop for the update clause.

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

<pre>
while (condition) {
multiLineStatement(
argument1, argument2);
}

while (condition1
&& condition2)
{
single_line_statement;
}
</pre>

Simple, single line body may omit curly braces:

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

An empty while statement should have the following form:

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

=== do-while Statements ===
A do-while statement should have the following form:

<pre>
do {
statements;
} while (condition);
</pre>

=== switch Statements ===
A <code>switch</code> statement should have the following form:

<pre>
<pre>
switch (condition) {
switch (condition) {
case ABC:
case ABC, DEF, KLM -> {
statements;
statements;
}
/* falls through */
case DEF:
case XYZ -> {
statements;
statements;
break;
}
default -> {
case KLM:
statements;
case XYZ:
statements;
}
break;
default:
statements;
break;
}
}
</pre>
</pre>


To use it, enable modern java syntax as [https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/master/gradle.properties#L33 shown] in the ExampleMod.
<code>case</code> is indented on the same level as <code>switch</code>.
Do not write unnecessary <code>break</code> and <code>default</code> when they can be avoided.
Comment fall-through cases.

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

=== try-catch Statements ===
A <code>try-catch</code> statement should have the following format:

<pre>
try {
statements;
} catch (ExceptionClass e) {
statements;
}
</pre>

A try-catch statement may also be followed by finally, which executes regardless of whether or not the try block has completed successfully.

<pre>
try {
statements;
} catch (ExceptionClass e) {
statements;
} finally {
statements;
}
</pre>

== White Space ==
=== Blank Lines ===
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 method declarations,
* 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 ===
Blank spaces should be used in the following circumstances:

1. A keyword followed by a parenthesis should be separated by a space. For example:

<pre>
while (true) {
...
}
</pre>

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.

2. A blank space should appear after commas in argument lists.
3. All binary operators except "." should be separated from their operands by spaces.
Blank spaces should never separate unary operators such as unary minus, increment ("++"), and decrement ("--") from their operands. Example:

<pre>
a += c + d;
a = (a + b) / (c * d);

while (d++ == s++) {
n++;
}
printSize("size is " + foo + "\n");
</pre>

4. The expressions in a for statement should be separated by spaces. Example:

<pre>
for (expr1; expr2; expr3)
</pre>

Casts should be followed by a blank space. Examples:

<pre>
myMethod((byte) aNum, (Object) x);
myMethod((int) (cp + 5), ((int) (i + 3)) + 1);
</pre>


== Naming ==
== Naming ==
Below is the table about most important naming conventions in the GTNH pack for the new code:
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.


{| class="wikitable"
{| class="wikitable"
|-
|-
! Identifier type !! Rules for Naming !! Examples
! Identifier type !! Rules for 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.
Subsequent components of the package name vary according to a GTNH internal naming conventions. (This generic description needs to be updated to the actual GTNH-one)
| com.sun.eng

com.apple.quicktime.v2

edu.cmu.cs.bovik.cheese
|-
|-
| Classes
| Classes
Line 585: Line 139:
|-
|-
| Interfaces
| Interfaces
| Interface names should be capitalized like class names. Do not use the "I" notation. For example, instead of IStorage, use Storage.
| Interface names should be capitalized like class names.
| interface RasterDelegate;
| interface RasterDelegate;
interface Storing;
interface Storing;
Line 592: Line 146:
| Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
| Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
| run();
| run();

runFast();


getBackgroundColor();
getBackgroundColor();
|-
| Test Methods
| Test Methods (methods in JUnit test classes annotated with @Test) can use one of the following styles:
* Classic style of 'test' followed by method name being tested and behavior using camel case.
* Test That style - naming methods starting with 'testThat' followed by the behavior being validated.
* Behavior-driven vocabulary with parts separated by underscores: methodName_StateUnderTest_ExpectedBehavior.
| testGetAccount();

testThatGetAccountThrowNotFoundException();

testThatGetAccountReturnsAccount();

getAccount_nullAccountId_throwsNotFoundException();

getAccount_validAccountId_returnsAccountObject();
|-
|-
| Variables
| Variables
| Variables should be named as mixed case with a lowercase first letter. Internal words start with capital letters.
| Variables should be named as mixed case with a lowercase first letter. Internal words start with capital letters.
Variable names should always start with an alphabetic character not underscore _ or dollar sign $.
Variable names should always start with an alphabetic character not underscore _ or dollar sign $.
Variable names should be short yet meaningful. The choice of a variable name should be mnemonic - that is, designed to indicate to the casual observer the intent of its use.
Variable names should be short yet meaningful. The choice of a variable name should be designed to indicate to the casual observer the intent of its use.
| String currentAccountKey;
One-character variable names should be avoided except for throwaway variables such as loop counters.
|}
| int i;


== GTNH-specific ==
String currentAccountKey;
==== Log formatting ====

For uniformity, most of log messages should use one write-call per line.
float myWidth;
One-sentence messages should not be capitalized. If there is more than one sentence, then capitalize.
|-
| Constants
| The names of variables declared as class constants and of ANSI constants should be all uppercase with words separated by underscores
("_"). ANSI constants should be avoided, for ease of debugging.
| static final int MIN_WIDTH = 4;

static final int MAX_WIDTH = 999;

static final int GET_THE_CPU = 1;
|}


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


==== Constants ====
=== Referring to Class Variables and Methods ===
Constants should not be coded directly. Please use well-named constants instead.
Avoid using an object to access a class (static) variable or method. Use a class name instead. For example:

<pre>
classMethod(); //OK
AClass.classMethod(); //OK
anObject.classMethod(); //AVOID!
</pre>

=== 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 <code>methodName(16281)</code>, the following is advised:
For example, instead of <code>methodName(16281)</code>, the following is advised:
Line 654: Line 173:
int CONSTANT_NAME = 16281;
int CONSTANT_NAME = 16281;


methodName(CONSTANT_EXPLANATION);
methodName(CONSTANT_NAME);
</pre>
</pre>


=== Variable assignments ===
==== Variable assignments ====
Avoid assigning several variables to the same value in a single statement. It is hard to read. Example:
Avoid assigning several variables to the same value in a single statement. It is hard to read. Example:


Line 664: Line 183:
</pre>
</pre>


==== Deprecation ====
Do not use the assignment operator in a place where it can be easily confused with the equality operator. Example:

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

Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler. Example:

<pre>
d = (a = b + c) + r; // AVOID!
// should be written as
a = b + c;
d = a + r;
</pre>

=== Deprecation ===
When using annotation @Deprecated, you must provide a comment referencing the solution that should be used instead.
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.
The @Deprecated annotation should always be present if the @deprecated javadoc tag is present, and vice-versa.
Line 700: Line 198:


== Miscellaneous Practices ==
== Miscellaneous Practices ==
=== Parentheses ===
==== 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.
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.


<pre>
<pre>
if ((a == b) && (c == d)) // OK
if (a == b && c == d) // AVOID!
if (a == b && c == d) // AVOID!
if ((a == b) && (c == d)) // RIGHT
</pre>

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

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

Similarly,

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

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

<pre>
(x >= 0) ? x : -x;
</pre>

Here are three acceptable ways to format ternary expressions:

<pre>
// 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;
</pre>

=== Special Comments ===
Use the <code>XXX</code> in a comment to flag something that is bogus but works.

Use <code>FIXME</code> to flag something that is bogus and broken.

=== stream API ===
Each <code>map, filter, flatMap, collect,</code> etc. method call should be placed on a new line.

<pre>
collection.stream()
.filter(...)
.forEach(...);
</pre>

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

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

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

=== Inner Classes ===
The following rule is applied to the inner classes
# All inner classes should be placed in the end of the file by default
# The exception of the rule one could be used when:
## Inner class definition does not exceed 30 lines of code and
## 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:

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

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.

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

==== Wrapping Lines ====
The following section is applicable only if [https://github.com/diffplug/spotless Spotless] doesn't work for some reason.

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:
<pre>
someMethod(longExpression1, longExpression2, longExpression3,
longExpression4, longExpression5);

var = someMethod1(tookTheFirstLine,
someMethod2(tookTheSecondLine,
longExpression3));
</pre>

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.
<pre>
longName1 = longName2 * (longName3 + longName4 - longName5)
+ 4 * longname6; // PREFER

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

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

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

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

Latest revision as of 17:46, 20 January 2024

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 the development easier.
  • Code conventions improve the readability, allowing developers to understand Pull Requests quicker.

The purpose of this Code Style is to provide a set of conventions that encourage good code.

Always practice good judgement. If following the guide causes unnecessary hoop-jumping or less-readable code, then readability trumps the guide. However, if the more "readable" variant comes with perils or pitfalls, then readability may be sacrificed.

In general, much of this Code Style is a summary of 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:

Spotless

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

File Organization

Files longer than 2000 lines are cumbersome and should be avoided.

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 public class variables, then protected, then package level (no access modifier), and then private.
5 Instance variables First public, then protected, then package level (no access modifier), and then private.
6 Constructors
7 Methods The 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.

Comments

  • Usually, code should not be commented out – delete it instead. If the code needed again, it will be available in the Git history.
  • 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 of asterisks or other characters.

Comment Styles

A single-line comment can use a double-slash notation:

if (foo > 1) {
    // Do a double-flip.
    return bar.performDoubleFlip();
}

If the comment spans multiple lines, then convert it to a block-comment:

codeGoesHere();

/*
 * Here is a block comment.
 */
moreCode();

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.

Declarations

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

Statements

switch Statements

It is suggested to use the following form:

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

To use it, enable modern java syntax as shown in the ExampleMod.

Naming

Below is the table about most important naming conventions in the GTNH pack for the new code:

Identifier type Rules for Naming Examples
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 they are widely used. class Raster

class ImageSprite

Interfaces Interface names should be capitalized like class names. interface RasterDelegate;

interface Storing;

Methods Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. run();

getBackgroundColor();

Variables Variables should be named as mixed case with a lowercase first letter. Internal words start with capital letters.

Variable names should always start with an alphabetic character not underscore _ or dollar sign $. Variable names should be short yet meaningful. The choice of a variable name should be designed to indicate to the casual observer the intent of its use.

String currentAccountKey;

GTNH-specific

Log formatting

For uniformity, most of log messages should use one write-call per line. One-sentence messages should not be capitalized. If there is more than one sentence, then capitalize.

Programming Practices

Providing Access to Instance and Class Variables

Don't make any instance or class variable public without good reason. Often instance variables are set or obtained as a side effect of method calls instead of being accessed directly.

Constants

Constants should not be coded directly. Please use well-named constants instead.

For example, instead of methodName(16281), the following is advised:

int CONSTANT_NAME = 16281;

methodName(CONSTANT_NAME);

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!

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<String, ?> params) {
    // <existing code>
}

Miscellaneous Practices

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!