Code Style: Difference between revisions

From GT New Horizons
Content added Content deleted
m (Replace syntaxhighlight with pre)
(Undo revision 10352 by Alastor's Game (talk))
 
(76 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.


The following table describes the parts of a class or interface declaration, in the order that they should appear.
Java source files have the following ordering:
* Beginning comments
* Package and Import statements
* Class and interface declaration(s)


{| class="wikitable"
==== 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.
! !!Part of Class/Interface Declaration !! Notes
|-
| 1 || Class/interface documentation comment (/**...*/) || Optional
|-
| 2 || <code>class</code> or <code>interface</code> 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 <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>.
|-
| 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 ==
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.
* 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:
<pre>
if (foo > 1) {
// Do a double-flip.
return bar.performDoubleFlip();
}
</pre>


If the comment spans multiple lines, then convert it to a block-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. For example:
<pre>
<pre>
codeGoesHere();
package java.awt;


/*
import java.awt.peer.CanvasPeer;
* Here is a block comment.
*/
moreCode();
</pre>
</pre>


==== Authorship ====
Imports should have separate section for java and javax, and mixed static (see below) and regular imports.
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 ==
Static imports are not used with the following exceptions:
==== Number Per Line ====
* Math.* if it's clear that numeric value passed as a parameter.
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:
* java.util.stream.Collectors
<pre>
* org.mockito.Mockito.* and org.mockito.ArgumentMatchers.* in tests
int x, y, z;
</pre>


Do not put different types on the same line. Example:
In tests, utility classes with assertion methods:
<pre>
* org.junit.Assert
int foo, fooarray[]; // AVOID!
* org.hamcrest.Matchers, CoreMatchers, Matcher, MatcherAssert and alike
</pre>
* org.junit.jupiter.api.Assertions and alike
* org.assertj.core.api.Assertions and alike


==== Initialization ====
As a result, the import part would look as follows:
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.
<pre>
<pre>
void myMethod() {
package
int int1 = 0; // beginning of method block


if (condition) {
import all other regular or static imports
int int2 = 0; // beginning of "if" block
...
}
}
</pre>


== Statements ==
import javax.*
==== switch Statements ====
import java.*
It is suggested to use the following form:
<pre>
switch (condition) {
case ABC, DEF, KLM -> {
statements;
}
case XYZ -> {
statements;
}
default -> {
statements;
}
}
</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.
==== Class and Interface Declarations ====

The following table describes the parts of a class or interface declaration, in the order that they should appear.
== Naming ==
Below is the table about most important naming conventions in the GTNH pack for the new code:


{| class="wikitable"
{| class="wikitable"
|-
|-
! Identifier type !! Rules for Naming !! Examples
! !!Part of Class/Interface Declaration !! Notes
|-
|-
| Classes
| 1 || Class/interface documentation comment (/**...*/) || Optional
| 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 <br>
class ImageSprite
|-
|-
| Interfaces
| 2 || <code>class</code> or <code>interface</code> statement ||
| Interface names should be capitalized like class names.
| interface RasterDelegate;
interface Storing;
|-
|-
| Methods
| 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.
| Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
| run();

getBackgroundColor();
|-
|-
| Variables
| 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>.
| 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 $.
| 5 || Instance variables || First <code>public</code>, then <code>protected</code>, then package level (no access modifier), and then <code>private</code>.
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;
| 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 ===
== GTNH-specific ==
==== Log formatting ====
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.
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 ==
GTNH code style overrides the Sun style by stating Tab characters - Sun leaves it unspecified.
==== Providing Access to Instance and Class Variables ====
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.


==== Line Length ====
==== Constants ====
Constants should not be coded directly. Please use well-named constants instead.
Avoid lines longer than 120 characters, since they're not handled well by many terminals and tools.


For example, instead of <code>methodName(16281)</code>, the following is advised:
GTNH Code Style overrides the Sun line length of 80 characters.
<pre>
int CONSTANT_NAME = 16281;


methodName(CONSTANT_NAME);
==== Wrapping Lines ====
</pre>
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
* The continuation on the next line shall be indented another single tab.


==== Variable assignments ====
Here are some examples of breaking method calls:
Avoid assigning several variables to the same value in a single statement. It is hard to read. Example:
<pre>
someMethod(longExpression1, longExpression2, longExpression3,
longExpression4, longExpression5);


<pre>
var = someMethod1(tookWholeFirstLine,
fooBar.fChar = barFoo.lchar = 'c'; // AVOID!
someMethod2(tookWholeSecondLine,
longExpression3));
</pre>
</pre>


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

<pre>
<pre>
/**
longName1 = longName2 * (longName3 + longName4 - longName5)
* @deprecated use {@link DBHelper#update(java.lang.String, java.util.Map)}
+ 4 * longname6; // PREFER
*/
@Deprecated(forRemoval = true)
public int insert(String request, Map<String, ?> params) {
// <existing code>
}
</pre>


== Miscellaneous Practices ==
longName1 = longName2 * (longName3 + longName4
==== Parentheses ====
- longName5) + 4 * longname6; // AVOID
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>
if ((a == b) && (c == d)) // OK
if (a == b && c == d) // AVOID!
</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!