---
title: Checkstyle
tags:
- 4 ๐ฅณ done
- checkstyle
- java
- style
- code-quality
- documentation
---
<!-- markdownlint-disable line-length single-h1 no-inline-html -->
<!-- markdownlint-configure-file { "ul-indent": { "indent": 4 }, "link-fragments": {"ignore_case": true} } -->
{%hackmd dJZ5TulxSDKme-3fSY4Lbw %}
# Understanding Checkstyle ๐งน
Checkstyle is a development tool that helps programmers write Java code that adheres to a coding standard. It automates the process of checking Java code to spare humans of this boring (but important) task.
## Why Style Matters? ๐ค
Code is read more than it's written. In fact:
- You spend 10x more time reading code than writing it
- Future you will thank present you for clean code
- Other developers need to understand your code
- Even AI tools work better with clean code!
:::success
๐ **Key Concept**
Good code style is not just about aesthetics - it's about making code more maintainable, readable, and less prone to errors. When code follows consistent style rules, developers can focus on understanding the logic rather than deciphering the structure.
:::
## Severity Levels in Our Configuration
Our Checkstyle configuration uses three severity levels:
### ๐ด ERROR (Must Fix)
- Wrong file names
- Missing braces
- Invalid package names
- Incorrect type names (class/interface names)
- Empty catch blocks (unless named 'expected')
### ๐ก WARNING (Should Fix)
- Variable naming conventions
- Method naming
- Indentation issues
- Brace placement
- One statement per line violations
- Modifier ordering
### ๐ต INFO (Good to Fix)
- Line length (>100 characters)
- Whitespace issues
- Tabs vs spaces
- Import ordering
- Empty line separation
:::warning
๐ง **Pitfall**: Even though some issues are marked as WARNING or INFO, they can still impact code quality. Don't ignore them just because they're not errors!
:::
## Key Style Rules
This is not all of the rules, but it's the most common concerns you might encounter.
### 1. Indentation
```java
// Correct (4 spaces)
public class Example {
public void method() {
if (condition) {
doSomething();
}
}
}
```
### 2. Naming Conventions
- Classes/Interfaces (PascalCase): `MyClass`
- Methods/Variables (camelCase): `myMethod`, `myVariable`
- Constants (UPPER_SNAKE_CASE): `MAX_VALUE`
- Packages (lowercase): `com.example.project`
### 3. Braces
```java
// Correct
if (condition) {
doSomething();
}
// Wrong
if (condition) doSomething();
```
### 4. Whitespace
```java
// Correct
for (int i = 0; i < 10; i++) {
method(a, b, c);
}
// Wrong
for(int i=0;i<10;i++){
method(a,b,c);
}
```
:::info
๐ง **Troubleshooting Tip**
Most whitespace and indentation issues can be automatically fixed using IntelliJ's auto-format feature (โโฅL / Ctrl+Alt+L).
:::
## Course vs Google Style
Our course uses a modified version of Google's Java Style Guide. The differences fall into two categories:
### Working with IntelliJ Defaults
These differences exist to work smoothly with IntelliJ's default settings:
1. **Indentation**
- Course: 4 spaces (basicOffset, caseIndent, arrayInitIndent)
- Google: 2 spaces
- **Rationale**: Working with IntelliJ's default indentation setting
2. **Empty Line Before Block Tags**
- Course: No requirement for empty line before block tags
- Google: Requires empty line before block tags
- **Rationale**: Better compatibility with IntelliJ's default Javadoc formatting
3. **Brace Adjustment**
- Course: Uses braceAdjustment="0"
- Google: Uses braceAdjustment="2"
- **Rationale**: Aligns with IntelliJ's default brace placement settings
### Course-Specific Choices
These differences reflect our course's pedagogical goals and priorities:
1. **Severity Levels**
- Course: Uses a tiered ERROR/WARNING/INFO system to help prioritize what to fix first
- Google: Generally enforces most rules strictly
- **Rationale**: Helps students focus on critical issues first while still learning about all aspects of good style
2. **Variable Declaration Usage Distance**
- Course: No restrictions on distance between variable declaration and first use
- Google: Enforces variables to be declared close to their first usage (within 3 lines)
- **Rationale**: Prioritizes learning and clarity over strict variable placement rules
3. **Empty Block Rule**
- Course: Adds EmptyBlock module with TEXT option for try/finally/if/else/switch blocks
- Google: No specific EmptyBlock module
- **Rationale**: Encourages explicit handling of empty blocks for better code clarity
4. **SummaryJavadoc Configuration**
- Course: No period requirement (period="")
- Google: Default period requirements
- **Rationale**: Focuses on content quality rather than punctuation formatting
5. **Package Name Pattern**
- Course: Uses pattern `"^[a-z][a-z0-9]+(\.[a-z][a-z0-9]*)*$"`
- Google: Uses pattern `"^[a-z]+(\.[a-z][a-z0-9]*)*$"`
- **Rationale**: Allows for package names to follow the assignment names (e.g., jam01 wouldn't be allowed by google because it doesn't allow number in the root package name)
6. **Constant Naming Convention**
- Course: Allows UPPER_CASE for constants (final fields)
- Google: Enforces camelCase even for constants
- **Rationale**: Follows traditional Java convention of using uppercase for constants, making them easily distinguishable in code
7. **One Top-Level Class**
- Course: Allows multiple top-level classes in a single file
- Google: Requires each top-level class to be in its own file
- **Rationale**: Enables pedagogically useful co-location of related code (e.g., enums and exceptions with their primary class)
:::info
๐ **Documentation Note**
Javadoc comments should be meaningful and help others understand your code. Simply having a Javadoc comment isn't enough - it needs to provide value to the reader. For example:
```java
// Good Javadoc
/**
* Calculates the average of an array of numbers.
*
* @param numbers The array of numbers to average
* @return The arithmetic mean of the numbers, or 0 if array is empty
* @throws IllegalArgumentException if the array is null
*/
public double average(double[] numbers)
// Bad Javadoc (doesn't add value)
/**
* Average method.
*
* @param numbers numbers
* @return the average
*/
public double average(double[] numbers)
```
:::
## IntelliJ Integration
IntelliJ helps you maintain good style with:
1. **Auto-format** (โโฅL / Ctrl+Alt+L)
- Fixes indentation
- Fixes whitespace
- Fixes brace placement
2. **Real-time checking**
- Shows style issues as you type
- Provides quick-fixes for common issues
## Common Issues and Fixes
1. **Indentation Issues**
```java
// Wrong
if (condition) {
doSomething(); // Wrong indent
}
// Correct
if (condition) {
doSomething(); // Proper 4-space indent
}
```
2. **Naming Problems**
```java
// Wrong
int x = 5; // Non-descriptive
String URL = "http://example.com"; // Uppercase for non-constant
// Correct
int count = 5; // Descriptive
String url = "http://example.com"; // Proper casing
```
3. **Brace Placement**
```java
// Wrong
if (condition)
doSomething();
// Correct
if (condition) {
doSomething();
}
```
:::danger
๐จ **Common Mistake**
One of the most common mistakes is forgetting braces for single-line if statements. Always use braces, even for single lines!
:::
## Tips for Success
1. **Use IntelliJ's Auto-Format Frequently**
- Before submitting code
- When pasting code
- When starting a new file
2. **Fix Issues Early**
- Address ERRORs immediately
- Don't let WARNINGs accumulate
- Consider INFO fixes for better readability
3. **Build Good Habits**
- Use proper naming from the start
- Maintain consistent indentation
- Add braces even for single-line blocks
## Resources
- [Google Java Style Guide](https://google.github.io/styleguide/javaguide.html)
- [Checkstyle Documentation](https://checkstyle.sourceforge.io/)
- Course Checkstyle Configuration (in your project)
- IntelliJ Shortcuts Guide
:::info
๐ฏ **Remember**
Clean code is not just about making it work - it's about making it work well and be maintainable for the future!
:::