Skip to content

Commit 124be42

Browse files
committed
docs(notes): add 2025-06-04-checkstyle-xml-en.md
1 parent ed2e1d6 commit 124be42

File tree

1 file changed

+178
-0
lines changed

1 file changed

+178
-0
lines changed

notes/2025-06-04-checkstyle-xml-en.md

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
---
2+
title: Checkstyle Configuration
3+
lang: en
4+
layout: post
5+
audio: false
6+
translated: false
7+
generated: true
8+
---
9+
10+
This is a Checkstyle configuration file written in XML, designed to enforce coding standards and best practices for Java code based on Sun's coding conventions, the Java Language Specification, Javadoc guidelines, and some additional best practices. Checkstyle is a static code analysis tool that checks Java source code for adherence to a set of defined rules. Below, I’ll explain the structure and key components of this configuration file.
11+
12+
---
13+
14+
### **Overview**
15+
- **Purpose**: The file defines rules for checking Java, properties, and XML files for coding standard violations, such as formatting, naming conventions, Javadoc requirements, and code structure.
16+
- **Structure**: The configuration is organized hierarchically using `<module>` elements, starting with a root `Checker` module, which contains other modules for specific checks or filters.
17+
- **Standards**: It aligns with:
18+
- Java Language Specification (Java SE 11)
19+
- Sun Code Conventions
20+
- Javadoc guidelines
21+
- JDK API documentation
22+
- General best practices
23+
- **Key Features**:
24+
- Configurable severity (set to `error`).
25+
- Supports file extensions: `.java`, `.properties`, `.xml`.
26+
- Allows suppression of specific checks via suppression files or `@SuppressWarnings` annotations.
27+
28+
---
29+
30+
### **Root Module: `<module name="Checker">`**
31+
The `Checker` module is the top-level module that orchestrates all checks and filters.
32+
33+
- **Properties**:
34+
- `severity="error"`: Treats all violations as errors (other options include `warning` or `info`).
35+
- `fileExtensions="java, properties, xml"`: Applies checks to `.java`, `.properties`, and `.xml` files.
36+
37+
- **Submodules**:
38+
- **File Filters**:
39+
- `BeforeExecutionExclusionFileFilter`: Excludes `module-info.java` files from checks (using regex `module\-info\.java$`).
40+
- **Suppression Filters**:
41+
- `SuppressionFilter`: Loads suppression rules from a file (default: `checkstyle-suppressions.xml`). If the file is missing, it’s optional (`optional="true"`).
42+
- `SuppressWarningsFilter`: Enables suppression of specific checks using `@SuppressWarnings("checkstyle:...")` annotations in code.
43+
- **Miscellaneous Checks**:
44+
- `JavadocPackage`: Ensures each package has a `package-info.java` file with Javadoc.
45+
- `NewlineAtEndOfFile`: Checks that files end with a newline character.
46+
- `Translation`: Verifies that property files (e.g., for internationalization) contain the same keys across translations.
47+
- **Size Checks**:
48+
- `FileLength`: Checks the total length of a file (default limits apply unless overridden).
49+
- `LineLength`: Ensures lines in `.java` files do not exceed a default length (typically 80 or 120 characters, configurable).
50+
- **Whitespace Checks**:
51+
- `FileTabCharacter`: Prohibits tab characters in source files (enforces spaces for indentation).
52+
- `RegexpSingleline`: Detects trailing whitespace (lines ending with `\s+$`) and reports them with the message "Line has trailing spaces."
53+
- **Header Check** (Commented Out):
54+
- `Header`: If uncommented, would enforce a specific file header (e.g., a copyright notice) from a file specified in `checkstyle.header.file` for `.java` files.
55+
56+
---
57+
58+
### **Submodule: `<module name="TreeWalker">`**
59+
The `TreeWalker` module processes the abstract syntax tree (AST) of Java source code to perform detailed checks. It contains a variety of submodules grouped by category.
60+
61+
#### **Javadoc Checks**
62+
These enforce proper Javadoc comments for classes, methods, and variables:
63+
- `InvalidJavadocPosition`: Ensures Javadoc comments are placed correctly (e.g., before a class or method, not elsewhere).
64+
- `JavadocMethod`: Checks that methods have proper Javadoc comments, including parameters, return types, and exceptions.
65+
- `JavadocType`: Ensures classes, interfaces, and enums have Javadoc comments.
66+
- `JavadocVariable`: Requires Javadoc for public/protected fields.
67+
- `JavadocStyle`: Enforces stylistic rules for Javadoc (e.g., proper HTML tags, no malformed comments).
68+
- `MissingJavadocMethod`: Flags methods missing Javadoc comments.
69+
70+
#### **Naming Conventions**
71+
These ensure that identifiers (variables, methods, classes, etc.) follow naming conventions:
72+
- `ConstantName`: Constants (e.g., `static final`) must follow a naming pattern (typically `UPPER_CASE`).
73+
- `LocalFinalVariableName`: Local `final` variables must follow a naming pattern (e.g., `camelCase`).
74+
- `LocalVariableName`: Local variables must follow a naming pattern (e.g., `camelCase`).
75+
- `MemberName`: Instance fields must follow a naming pattern (e.g., `camelCase`).
76+
- `MethodName`: Methods must follow a naming pattern (e.g., `camelCase`).
77+
- `PackageName`: Packages must follow a naming pattern (e.g., lowercase with dots, like `com.example`).
78+
- `ParameterName`: Method parameters must follow a naming pattern (e.g., `camelCase`).
79+
- `StaticVariableName`: Static (non-final) fields must follow a naming pattern.
80+
- `TypeName`: Class/interface/enum names must follow a naming pattern (e.g., `UpperCamelCase`).
81+
82+
#### **Import Checks**
83+
These regulate the use of `import` statements:
84+
- `AvoidStarImport`: Prohibits wildcard imports (e.g., `import java.util.*`).
85+
- `IllegalImport`: Blocks imports from restricted packages (defaults to `sun.*`).
86+
- `RedundantImport`: Flags duplicate or unnecessary imports.
87+
- `UnusedImports`: Detects unused imports (ignores Javadoc-related imports with `processJavadoc="false"`).
88+
89+
#### **Size Checks**
90+
These limit the size of methods and parameters:
91+
- `MethodLength`: Ensures methods do not exceed a maximum number of lines (default typically 150).
92+
- `ParameterNumber`: Limits the number of parameters in a method (default typically 7).
93+
94+
#### **Whitespace Checks**
95+
These enforce consistent use of whitespace in code:
96+
- `EmptyForIteratorPad`: Checks padding in empty `for` loop iterators (e.g., `for (int i = 0; ; i++)`).
97+
- `GenericWhitespace`: Ensures proper spacing around generic types (e.g., `List<String>`).
98+
- `MethodParamPad`: Checks spacing before method parameter lists.
99+
- `NoWhitespaceAfter`: Prohibits whitespace after certain tokens (e.g., `++` or arrays).
100+
- `NoWhitespaceBefore`: Prohibits whitespace before certain tokens (e.g., semicolons).
101+
- `OperatorWrap`: Ensures operators (e.g., `+`, `=`) are on the correct line.
102+
- `ParenPad`: Checks spacing inside parentheses (e.g., `( x )` vs. `(x)`).
103+
- `TypecastParenPad`: Ensures proper spacing in typecasts.
104+
- `WhitespaceAfter`: Requires whitespace after certain tokens (e.g., commas, semicolons).
105+
- `WhitespaceAround`: Ensures whitespace around operators and keywords (e.g., `if (x == y)`).
106+
107+
#### **Modifier Checks**
108+
These regulate the use of Java modifiers:
109+
- `ModifierOrder`: Ensures modifiers are in the correct order (e.g., `public static final`, per JLS).
110+
- `RedundantModifier`: Flags unnecessary modifiers (e.g., `final` in a `final` class).
111+
112+
#### **Block Checks**
113+
These enforce proper use of code blocks (`{}`):
114+
- `AvoidNestedBlocks`: Prohibits unnecessary nested blocks (e.g., `{ { ... } }`).
115+
- `EmptyBlock`: Flags empty blocks (e.g., `{}`) unless intentional.
116+
- `LeftCurly`: Ensures opening braces (`{`) are placed correctly (e.g., at the end of a line).
117+
- `NeedBraces`: Requires braces for single-statement blocks (e.g., `if (x) y();` must be `if (x) { y(); }`).
118+
- `RightCurly`: Ensures closing braces (`}`) are placed correctly (e.g., on a new line or same line, depending on style).
119+
120+
#### **Coding Problem Checks**
121+
These identify common coding issues:
122+
- `EmptyStatement`: Flags empty statements (e.g., `;;`).
123+
- `EqualsHashCode`: Ensures that if `equals()` is overridden, `hashCode()` is also overridden.
124+
- `HiddenField`: Detects fields shadowed by local variables or parameters.
125+
- `IllegalInstantiation`: Prohibits instantiation of certain classes (e.g., `java.lang` classes like `String`).
126+
- `InnerAssignment`: Disallows assignments within expressions (e.g., `if (x = y)`).
127+
- `MagicNumber`: Flags hardcoded numeric literals (e.g., `42`) unless in specific contexts.
128+
- `MissingSwitchDefault`: Requires a `default` case in `switch` statements.
129+
- `MultipleVariableDeclarations`: Prohibits declaring multiple variables in a single line (e.g., `int x, y;`).
130+
- `SimplifyBooleanExpression`: Flags overly complex boolean expressions (e.g., `if (x == true)`).
131+
- `SimplifyBooleanReturn`: Simplifies boolean return statements (e.g., `if (x) return true; else return false;`).
132+
133+
#### **Class Design Checks**
134+
These enforce good class design practices:
135+
- `DesignForExtension`: Ensures non-final classes have protected or abstract methods for extensibility.
136+
- `FinalClass`: Flags classes with only private constructors as candidates for `final`.
137+
- `HideUtilityClassConstructor`: Ensures utility classes (with only static members) have private constructors.
138+
- `InterfaceIsType`: Prohibits interfaces used solely as marker interfaces (without methods).
139+
- `VisibilityModifier`: Enforces proper visibility for fields (e.g., prefers private fields with getters/setters).
140+
141+
#### **Miscellaneous Checks**
142+
- `ArrayTypeStyle`: Enforces consistent array declaration style (e.g., `int[]` vs. `int []`).
143+
- `FinalParameters`: Requires method parameters to be `final` where possible.
144+
- `TodoComment`: Flags `TODO` comments in code (useful for tracking incomplete work).
145+
- `UpperEll`: Ensures the letter `L` is used for long literals (e.g., `100L` instead of `100l`).
146+
147+
#### **Suppression Filters (Inside TreeWalker)**
148+
- `SuppressionXpathFilter`: Allows suppression of checks using XPath expressions defined in a file (default: `checkstyle-xpath-suppressions.xml`, optional).
149+
- `SuppressWarningsHolder`: Supports `@SuppressWarnings("checkstyle:...")` annotations for suppressing specific checks within the AST.
150+
151+
---
152+
153+
### **Key Points**
154+
- **Configurability**: Most modules have default settings but can be customized via properties (e.g., `LineLength` can set a specific `max` length).
155+
- **Suppression**: The configuration supports flexible suppression of checks via external files (`checkstyle-suppressions.xml`, `checkstyle-xpath-suppressions.xml`) or annotations.
156+
- **Extensibility**: Additional checks can be added, and existing ones can be disabled by commenting them out or removing them.
157+
- **Documentation**: The configuration references Checkstyle’s documentation (e.g., `https://checkstyle.org`) for details on each module.
158+
- **Header Check**: The `Header` module is commented out, so it’s not active unless uncommented and configured with a header file.
159+
160+
---
161+
162+
### **How It’s Used**
163+
1. **Integration**: This file is typically used with a build tool like Maven, Gradle, or an IDE plugin to run Checkstyle during the build process or in development.
164+
2. **Violation Reporting**: When code violates a rule (e.g., a line exceeds the maximum length), Checkstyle reports it as an error (due to `severity="error"`).
165+
3. **Suppression**: Developers can suppress specific violations using `@SuppressWarnings("checkstyle:<check-name>")` or by defining rules in suppression files.
166+
4. **Customization**: Properties like `basedir`, `checkstyle.header.file`, or suppression file paths can be set externally (e.g., via build tool configurations).
167+
168+
---
169+
170+
### **Example Violations**
171+
- **JavadocMethod**: A public method without Javadoc will trigger an error.
172+
- **LineLength**: A line in a `.java` file exceeding the default max (e.g., 80 characters) will be flagged.
173+
- **AvoidStarImport**: Using `import java.util.*` will cause an error.
174+
- **MagicNumber**: Writing `int x = 42;` without a named constant will be flagged.
175+
176+
---
177+
178+
If you need a deeper explanation of a specific module, examples of violations, or guidance on customizing this configuration, let me know!

0 commit comments

Comments
 (0)