In the world of software development, code is not only the cornerstone of programs but also the universal language through which programmers communicate. As a widely used programming language for enterprise-level applications, Java's code readability and consistency are crucial for long-term project maintenance and team collaboration. This article will explore the aesthetics of Java code, unveiling the style guidelines that can make your code both elegant and efficient. Whether you are a novice just starting out or an experienced developer, you can draw inspiration from these guidelines to enhance your coding skills.
1. Why Code Style Guidelines Matter
In team development, differences in code conventions or lack of conventions can lead to various issues, including but not limited to:
Code Readability: Code is meant to be read by humans, not just executed by machines.
Code Formatting Issues: Inconsistent formatting can lead to numerous diffs, making code reviews more difficult.
Indirect Impact on Code Quality and Team Collaboration Efficiency: Poorly formatted code can reduce the effectiveness of team collaboration and increase the time spent on maintenance.
In an agile, iterative software development environment, good coding standards not only help team members quickly understand each other's code and reduce communication costs, but also save valuable time when maintaining and expanding the code. Additionally, consistent coding style reflects professionalism, leaving a good first impression on code reviewers and future maintainers.
2. Exploring Java Code Standards
We will delve into widely recognized Java coding standards, including but not limited to Google Java Style and the official Oracle coding guidelines. From naming conventions, code formatting, and the use of comments to error handling and writing test code, every detail plays a crucial role in building high-quality Java code.
2.1 Industry Java Coding Standards
a. Google Java Style
Google maintains coding standards for various programming languages on GitHub: Google Style Guide. Specifically for Java:
javaguide.html: Complete definition of Google's Java coding standards.
intellij-java-google-style.xml: A Google Java style configuration file for use in IntelliJ IDEA.
b. Alibaba Java Standards
Alibaba also has a Java development standards repository on GitHub: https://github.com/alibaba/p3c, which includes:
Java Development Manual (Huangshan Edition): Covers seven dimensions such as programming conventions, exception logging, and unit testing.
Alibaba Java Coding Guidelines Plugin: A code guidance plugin for JetBrains IDEs, available in the JetBrains Plugin Marketplace, along with installation and usage instructions.
c. Other Standards
Other notable coding standards include:
Organization/Company | Style Guide |
---|---|
Sun/Oracle | The Original Sun Java Style Guide |
Android | Android Open Source Project (AOSP) Style Guide |
Twitter’s Java Style Guide | |
CodeRanch | The CodeRanch Style Guide |
2.2 Choosing and Establishing a Coding Standard
a. Choosing a Standard
When deciding which standard to adopt, consider the following three aspects:
Clear Objective: Is the goal to maintain consistency within a project, share code with other teams or companies, or open-source the project?
Development Environment: Where will the code be read or shared? GitHub, GitLab, or internally within the company?
Tool Support: Ensure the tools (e.g., code formatters, style checkers, build tools like Maven or Gradle, IDEs such as IntelliJ, Eclipse, VS Code) support the chosen style.
Given these considerations, Google's Java Style is generally a good first choice.
b. Establishing a Custom Standard
Some aspects of Google's Java Style, like using 2-space indentation, may not be suitable for every team. In such cases, you can customize Google’s Java Style according to your needs.
Modify the intellij-java-google-style.xml configuration file:
Option | Previous Value | Modified Value | Note |
---|---|---|---|
INDENT_SIZE | 2 | 4 | Number of spaces for indentation |
TAB_SIZE | 2 | 4 | Number of spaces for a tab |
CONTINUATION_INDENT_SIZE | 4 | 8 | Indentation for line continuation |
RIGHT_MARGIN | 100 | 120 | Maximum line length |
JD_PRESERVE_LINE_FEEDS | None | TRUE | Retain manual line breaks in JavaDocs |
KEEP_LINE_BREAKS | None | TRUE | Retain manual line breaks in Java code |
Modify the intellij-java-jd-style.xml file: Download Link
2.3 Applying the Standard
The use of coding standards can be broken down into two key areas:
Code Formatting
Code Style Checking
Standard Use | English | Audience | Method | Description | Configuration File |
---|---|---|---|---|---|
Code Formatting | Code Style | Developers | Manual in IDE | Defines the code style | intellij-java-jd-style.xml |
Code Style Checking | Check Style | Team | Automated | Checks code style | checkstyle.xml |
Note: The configuration files for "code style" and "check style" must match to avoid errors during style checking.
Code Style Checking:
Code formatting relies on manual efforts by developers, but to enforce team or project-wide code style consistency, automated code checks are necessary. The industry standard tool for this is Checkstyle.
Customization of the Google Code Style's google_checks configuration is required to align it with the customizations in intellij-java-jd-style.xml.
Modify the google_checks configuration:
Module | Property | Previous Value | Modified Value | Note |
---|---|---|---|---|
LineLength | max | 100 | 120 | Maximum line length |
Indentation | basicOffset, braceAdjustment, caseIndent, etc. | 2, 2, 2, 4, 4, 2 | 4, 0, 4, 4, 4, 4 | Use default Checkstyle indentation style |
Modify the checkstyle.xml file: Download Link
In addition to length and indentation checks, Checkstyle can be configured for other code checks, depending on the team's needs.
Module | Property | Default Value | Note |
---|---|---|---|
FileLength | max | 2000 | Maximum file length |
MethodLength | max | 150 | Maximum method length |
ParameterNumber | max | 7 | Maximum number of method parameters |
ModifierOrder | - | - | Java language conventions |
NestedIfDepth | max | 1 | Max nesting level for if-else statements |
NestedTryDepth | max | 1 | Max nesting level for try-catch-finally blocks |
ReturnCount | max | 2 | Maximum number of returns in a method |
CyclomaticComplexity | max | 10 | Maximum cyclomatic complexity of a method |
MagicNumber | - | - | Detect magic numbers (unassigned constants) |
3. Best Practices: Integrating Coding Standards into Daily Development
3.1 Code Style Configuration & Usage
a. Configuring Code Style in IDEA
Before using the intellij-java-jd-style.xml
file for code formatting in IntelliJ IDEA, you need to configure it first.
Set up the configuration file. Navigate to IntelliJ IDEA → Preferences → Editor → Code Style, as shown in the figure below:
Import the customized code style file:
intellij-java-jd-style.xml
.
Name the scheme (e.g., "JD-Style") and enable the code style configuration.
b. Using Code Style in IDEA
After completing the above configuration, in IntelliJ IDEA on a Mac environment, you can format selected code using the shortcut Option + Command + L
, or format an entire file using Shift + Option + Command + L
.
3.2 CheckStyle Configuration & Usage
There are two primary ways to configure and use CheckStyle:
In the development environment (IDE), after configuring the plugin, developers can trigger code style checks and make code changes based on the prompts.
In a Maven project, configure the CheckStyle plugin to trigger code style checks via the command line and integrate it into the Continuous Integration (CI) pipeline.
a. Configuring the CheckStyle Plugin in IDEA
In IntelliJ IDEA, install the CheckStyle plugin. Navigate to IntelliJ IDEA → Preferences → Plugins, as shown in the figure below:
Download the configuration file
checkstyle.xml
and configure it in the CheckStyle-IDEA plugin. Navigate to IntelliJ IDEA → Preferences → Tools → Checkstyle, add the custom configuration file, and give it a name as shown below:
b. Using the CheckStyle Plugin in IDEA
After installing and configuring the CheckStyle plugin, a CheckStyle Tab will appear in the tool window. In the CheckStyle window, you can select one of the following options:
Check Current File
Check Module
Check Project
c. Configuring CheckStyle Plugin in Maven
Refer to the official configuration example for the CheckStyle Maven plugin, which includes multi-module project setup. Typically, a new build-tools
module is created in the project, where configuration files like checkstyle.xml
are placed under the resources
directory.
project-name | -- pom.xml | -- build-tools | -- pom.xml | -- src | | -- main | | | -- resources | | | | -- checkstyle.xml | | | | -- checkstyle-suppressions.xml | -- core | -- gui | -- other-module
In the build-tools
module, the pom.xml
file is typically generated by IDEA, similar to this:
<?xml version="1.0" encoding="UTF-8"?> <project> <parent> <artifactId>project-name</artifactId> <groupId>com.jd.project-name</groupId> <version>1.0.0</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>build-tools</artifactId> </project>
You can download the configuration files (checkstyle.xml
and checkstyle-suppressions.xml
) from here.
In the parent project’s pom.xml
, add the following configuration:
<project> ... <modules> ... <module>build-tools</module> </modules> <properties> ... <maven.checkstyle.version>3.6.0</maven.checkstyle.version> </properties> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>${maven.checkstyle.version}</version> <configuration> <configLocation>build-tools/src/main/resources/checkstyle.xml</configLocation> <includeTestSourceDirectory>true</includeTestSourceDirectory> <outputFile>checkstyle-report.xml</outputFile> <consoleOutput>false</consoleOutput> <failOnViolation>true</failOnViolation> <excludes>target/**</excludes> </configuration> <executions> <execution> <id>checkstyle</id> <phase>validate</phase> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <reportSets> <reportSet> <reports> <report>checkstyle</report> </reports> </reportSet> </reportSets> </plugin> </plugins> </reporting> </project>
The configuration in the pom.xml
file for the Checkstyle Maven Plugin can be found in the Checkstyle plugin documentation. Below are some explanations of key configurations:
plugins → plugin → executions → execution
The
id
can be customized (e.g., "checkstyle").The
phase
binds the execution to a Maven lifecycle phase, here it's bound to thevalidate
phase. This ensures that Checkstyle checks run before code compilation, reporting violations before Java compilation starts.The
goals → goal
specifies which task to bind; in this case, it's set tocheck
.plugins → plugin → configuration → failOnViolation
If violations are detected, they are printed. The severity level is defined in
checkstyle.xml
.Set
failOnViolation
totrue
and the severity toerror
to stop Maven execution when violations are found.
With the above configuration, code style violations will prevent further Java compilation or packaging.
d. Using the CheckStyle Plugin in Maven
To trigger the check, run the following Maven command:
mvn checkstyle:check
Alternatively, you can run the project as usual with:
mvn package
To implement automated code style checks, configure a Continuous Integration (CI) pipeline that checks code review tasks. The pipeline should run successfully before the Merge Request (MR) can be merged.
4. Conclusion: Code Style as a Bridge for Team Collaboration
In conclusion, we emphasize the importance of Java style guidelines for team collaboration and encourage developers to internalize these practices into their coding habits. Code standards are not only a reflection of individual skills but also the foundation for successful team collaboration and project success.
By reading this article, you will not only understand the importance of Java style guidelines but also learn how to apply them to real-world development, making your code more elegant and powerful. Let’s pursue the art of coding together and illuminate the programming world with standardized code.
References
JD Coding Standards: JD Coding Standards
JetBrains Java Code Style: IntelliJ IDEA Documentation
Checkstyle Official Website: Checkstyle
Checkstyle Release: Checkstyle GitHub Releases
Apache Maven Checkstyle Plugin: Maven Checkstyle Plugin Documentation