The Beauty of Java Code: Starting with Adhering to Style Guidelines

Time: Column:Java views:261

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:

  1. Code Readability: Code is meant to be read by humans, not just executed by machines.

  2. Code Formatting Issues: Inconsistent formatting can lead to numerous diffs, making code reviews more difficult.

  3. 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:

b. Alibaba Java Standards

Alibaba also has a Java development standards repository on GitHub: https://github.com/alibaba/p3c, which includes:

c. Other Standards

Other notable coding standards include:

Organization/CompanyStyle Guide
Sun/OracleThe Original Sun Java Style Guide
AndroidAndroid Open Source Project (AOSP) Style Guide
TwitterTwitter’s Java Style Guide
CodeRanchThe 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:

OptionPrevious ValueModified ValueNote
INDENT_SIZE24Number of spaces for indentation
TAB_SIZE24Number of spaces for a tab
CONTINUATION_INDENT_SIZE48Indentation for line continuation
RIGHT_MARGIN100120Maximum line length
JD_PRESERVE_LINE_FEEDSNoneTRUERetain manual line breaks in JavaDocs
KEEP_LINE_BREAKSNoneTRUERetain manual line breaks in Java code

2.3 Applying the Standard

The use of coding standards can be broken down into two key areas:

  • Code Formatting

  • Code Style Checking

Standard UseEnglishAudienceMethodDescriptionConfiguration File
Code FormattingCode StyleDevelopersManual in IDEDefines the code styleintellij-java-jd-style.xml
Code Style CheckingCheck StyleTeamAutomatedChecks code stylecheckstyle.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.

ModulePropertyPrevious ValueModified ValueNote
LineLengthmax100120Maximum line length
IndentationbasicOffset, braceAdjustment, caseIndent, etc.2, 2, 2, 4, 4, 24, 0, 4, 4, 4, 4Use default Checkstyle indentation style

In addition to length and indentation checks, Checkstyle can be configured for other code checks, depending on the team's needs.

ModulePropertyDefault ValueNote
FileLengthmax2000Maximum file length
MethodLengthmax150Maximum method length
ParameterNumbermax7Maximum number of method parameters
ModifierOrder--Java language conventions
NestedIfDepthmax1Max nesting level for if-else statements
NestedTryDepthmax1Max nesting level for try-catch-finally blocks
ReturnCountmax2Maximum number of returns in a method
CyclomaticComplexitymax10Maximum cyclomatic complexity of a method
MagicNumber
--

Detect magic numbers (unassigned constants)

checkstyle – Checks


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.

  1. Set up the configuration file. Navigate to IntelliJ IDEA → Preferences → Editor → Code Style, as shown in the figure below:

  2. Import the customized code style file: intellij-java-jd-style.xml.

1 (13).png

  1. Name the scheme (e.g., "JD-Style") and enable the code style configuration.

2 (14).png

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 (8).png

3.2 CheckStyle Configuration & Usage

There are two primary ways to configure and use CheckStyle:

  1. In the development environment (IDE), after configuring the plugin, developers can trigger code style checks and make code changes based on the prompts.

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

  1. In IntelliJ IDEA, install the CheckStyle plugin. Navigate to IntelliJ IDEA → Preferences → Plugins, as shown in the figure below:

    4 (6).png

  2. 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:

    5 (4).png

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

6 (2).png

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 the validate 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 to check.

  • plugins → plugin → configuration → failOnViolation

    • If violations are detected, they are printed. The severity level is defined in checkstyle.xml.

    • Set failOnViolation to true and the severity to error 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