D

Context

I'm standardizing code quality across my Minecraft plugin development workflow. I use an AI assistant to generate plugin code, but the output often lacks polish — inconsistent formatting, poor naming, missing Javadocs, and subtle bugs that only show up under load. I need a comprehensive, downloadable reference that I can keep open while reviewing AI-generated code.

Request

Generate a complete Minecraft Plugin Code Quality & Polish Standards Guide and provide it as a downloadable file (.md or .txt). This should be a standalone document I can distribute to my team, print, or search through offline when auditing plugins.

Document Title

Plugin_Code_Quality_Standards.md

Required Structure

markdown
# Minecraft Plugin Code Quality & Polish Standards
## Paper 1.21.4 — Production-Ready Code Review Checklist

---

## 1. Naming Conventions
### 1.1 Class Naming Strategy
### 1.2 Method Naming Patterns
### 1.3 Variable & Field Naming
### 1.4 Constants & Enums
### 1.5 Package Naming Rules

## 2. Code Organization & Readability
### 2.1 The 50-Line Method Rule
### 2.2 Import Organization & Wildcard Policy
### 2.3 Annotation Discipline
### 2.4 Brace Style & Indentation
### 2.5 Single Responsibility Principle for Classes

## 3. Documentation Standards
### 3.1 Javadoc Requirements (MUST vs SHOULD vs OPTIONAL)
### 3.2 Self-Documenting Code vs Comments
### 3.3 plugin.yml Metadata Standards
### 3.4 README & Documentation Files

## 4. Error Handling Elegance
### 4.1 Exception Philosophy (Checked vs Unchecked)
### 4.2 Try-Catch Placement & Scope
### 4.3 Empty Catch Blocks — The Ultimate Sin
### 4.4 Logging Standards (Never e.printStackTrace())
### 4.5 Null Safety Patterns

## 5. Resource Management
### 5.1 Try-With-Resources for AutoCloseables
### 5.2 Listener Lifecycle (Register → Unregister)
### 5.3 Task Lifecycle (Schedule → Cancel)
### 5.4 Connection & Stream Cleanup

## 6. Plugin Lifecycle Discipline
### 6.1 onEnable() — What Belongs, What Doesn't
### 6.2 onDisable() — Cleanup Checklist
### 6.3 onLoad() — When to Use (Rarely)
### 6.4 Reload-Safe Architecture

## 7. Configuration & Messaging Standards
### 7.1 Type-Safe Config Wrappers
### 7.2 Message Externalization (No Hardcoded Strings)
### 7.3 Color Code & Component Standards
### 7.4 Config Validation at Load Time

## 8. Common AI Polish Failures (30+ Examples)
### 8.1 Formatting Issues
### 8.2 Naming Inconsistencies
### 8.3 Logic Red Flags
### 8.4 Performance Anti-Patterns in Style
### 8.5 Security Style Issues

---

## Appendix A: 30-Point Pre-Commit Checklist
## Appendix B: Code Review Red Flags (Visual Scanning Guide)
## Appendix C: AI Prompt Engineering Phrases for Better Output
## Appendix D: Auto-Format Configuration (IntelliJ / VSCode / Eclipse)

Detailed Content Requirements

1. Naming Conventions

Class Names:

  • Main class: PluginName vs PluginNamePlugin vs PluginNameMain — which is correct and WHY
  • Manager classes: PlayerManager vs PlayerDataManager vs PlayerService — when to use each suffix
  • Listener classes: PlayerJoinListener vs PlayerListener — one event per class or grouped?
  • Command classes: ReloadCommand vs CommandReload — prefix vs suffix convention
  • Utility classes: Utils vs StringUtils vs PluginUtils — when is a static utility class acceptable?
  • API classes: MyPluginAPI vs PluginNameAPI — naming for external consumption
  • Exception classes: PluginException naming hierarchy

Method Names:

  • Event handlers: onPlayerJoin(PlayerJoinEvent e) vs handleJoin(PlayerJoinEvent e) vs playerJoin(PlayerJoinEvent e)
  • Command executors: onCommand() vs execute() vs run() — which to override vs implement
  • Boolean getters: isEnabled() vs hasPermission() vs canBuild() — prefix conventions table
  • Action methods: loadConfig() vs configLoad() vs initializeConfig() — verb-first imperative rule
  • Async methods: loadPlayerDataAsync() naming convention
  • Callback methods: onDataLoaded(), whenComplete() patterns

Variable & Field Names:

  • Plugin instance field: instance, plugin, pl — which is standard?
  • Logger: logger, log, LOGGER — static final vs instance field?
  • Config fields: config, cfg, configuration — consistency matters
  • Player cache: playerData, dataMap, cache — descriptive vs concise balance
  • Constants: MAX_PLAYERS, DEFAULT_TIMEOUT, CHAT_FORMAT — when to use UPPER_SNAKE_CASE
  • Private fields: prefix with underscore? Hungarian notation? Modern convention?

For EACH naming topic, provide:

  1. The convention rule
  2. Why it matters (readability, searchability, API consistency)
  3. Common AI mistake (what it generates)
  4. The corrected version
  5. Edge cases and exceptions

2. Code Organization

The 50-Line Method Rule:

  • When should a method be split? Give specific Minecraft plugin examples
  • Event handler max length: 20 lines? 30 lines? What's the threshold?
  • Command executor length: How to keep onCommand() under 15 lines using subcommand routing
  • Refactoring pattern: Extract method, extract class, introduce parameter object

Import Organization:

  • Group imports: java. → bukkit/paper. → external libraries → internal project
  • Wildcard imports (import org.bukkit.*) — acceptable or evil? When?
  • Static imports for ChatColor — convenient or confusing?
  • Unused imports: IDE auto-cleanup vs manual review

Annotation Discipline:

  • @Override — when is it mandatory vs optional? (Hint: always use it)
  • @EventHandler — same line or above? Priority parameter formatting
  • @Nullable / @NotNull — should we use JetBrains annotations? JSR-305? Eclipse?
  • @Deprecated with Javadoc — how to properly mark deprecated methods with replacement
  • @SuppressWarnings — when justified vs laziness

3. Documentation Standards

Javadoc Requirements:

  • What MUST be documented: Public API methods, event handlers, command classes, manager constructors
  • What SHOULD be documented: Complex algorithms, database operations, async boundaries, configuration keys
  • What's OPTIONAL: Simple getters, obvious event handlers, standard overrides
  • Main class header: What information belongs in class-level Javadoc? (author, version, description, link)
  • Package-info.java: When to use it?

Self-Documenting Code vs Comments:

  • When is a comment a "code smell" indicating the code should be refactored?
  • "What" comments vs "Why" comments — which adds value?
  • Example of bad comment: // Increment i by 1 next to i++
  • Example of good comment: // Paper API requires synchronous teleport even though event is async
  • Comment maintenance: outdated comments are worse than no comments

plugin.yml Metadata:

  • description: Sales pitch or technical summary? Length recommendations
  • website: When to include vs omit?
  • authors vs author: Array vs single string — which is preferred?
  • api-version: Format, why it matters, common mistakes
  • softdepend vs depend: When to use each, ordering

4. Error Handling

Exception Philosophy:

  • Checked vs unchecked exceptions in plugin development — which to prefer?
  • When to create custom exceptions (PluginException, DatabaseException)
  • Runtime exceptions for programmer errors, checked for recoverable conditions?
  • Exception translation: SQLException → domain exception at repository boundary

Try-Catch Placement:

  • Around entire method or specific risky calls?
  • Nested try-catch vs multiple catch blocks vs multi-catch
  • catch (Exception e) — when is it acceptable? (Answer: almost never)

Empty Catch Blocks:

  • Show AI-generated bad example and correct version
  • What to do when you genuinely want to swallow an exception (rare, but documented)
  • Logging the exception without crashing: getLogger().log(Level.WARNING, "...", e)

Logging Standards:

  • e.printStackTrace() — why this is banned in production
  • getLogger().info/debug/warning/severe() — appropriate levels
  • System.out.println — banned entirely
  • SLF4J / Log4J integration in modern Paper
  • Structured logging: including context (player name, UUID, world) in log messages

Null Safety:

  • Optional<Player> vs @Nullable annotation vs null-checks — which pattern for which scenario?
  • Early return vs deep nesting: if (player == null) return; vs nested if-blocks
  • Null object pattern: When to use Player.EMPTY instead of null checks
  • Objects.requireNonNull() — when to use at API boundaries
  • Common AI mistake: Assuming event.getPlayer() is never null

5. Resource Management

Try-With-Resources:

  • Every AutoCloseable MUST use try-with-resources. No exceptions.
  • Proper nesting: PreparedStatement + ResultSet + Connection
  • Common AI mistake: Connection conn = ...; conn.close(); without try-finally
  • Show complete, correct JDBC resource pattern

Listener Lifecycle:

  • Register in onEnable() → Unregister in onDisable() — non-negotiable rule
  • What happens if you don't unregister? (Memory leak explanation with technical detail)
  • Dynamic listeners (registered mid-runtime): When are they appropriate?
  • Listener class state: Should listeners hold state or be stateless?

Task Management:

  • Every BukkitRunnable or BukkitTask MUST be stored and cancelled
  • Task ID tracking: Map<UUID, Integer> for per-player repeating tasks
  • Global task cleanup: Collection<BukkitTask> for plugin-wide tasks
  • Common AI mistake: Scheduling a repeating task without storing the task ID
  • Task naming: Why you should name your runnables for debugging

6. Plugin Lifecycle

onEnable() — What Belongs:

  • Configuration loading (fail fast if invalid)
  • Database connection initialization
  • Manager initialization (in order: config → database → player data → commands → listeners)
  • Command registration
  • Listener registration
  • API registration (for other plugins)
  • Metrics initialization (optional)

onEnable() — What DOESN'T Belong:

  • Heavy computation (move to async)
  • Network requests (move to async with callback)
  • World manipulation (schedule for next tick)
  • Player iteration (world may not be fully loaded)

onDisable() — Cleanup Checklist:

  • Save all player data
  • Cancel all scheduled tasks
  • Unregister all listeners
  • Close all database connections
  • Release all cached resources
  • Notify dependent plugins (if API exposed)
  • Log shutdown message

Reload-Safe Architecture:

  • Why plugin.reload() is dangerous (listener duplication, task leakage)
  • Proper reload: Disable → re-init config → re-register → enable pattern
  • State preservation across reloads (what to keep, what to reset)

7. Configuration & Messaging

Type-Safe Config Wrappers:

  • Why getConfig().getString("path") scattered everywhere is bad
  • Config wrapper class: ConfigManager.getMessage("welcome") vs getConfig().getString("messages.welcome")
  • Default values: every config access must have fallback
  • Config validation at load: fail fast with descriptive messages
  • Hot reload considerations: atomic swap, don't mutate active config

Message Externalization:

  • ZERO hardcoded strings in source code (except constants)
  • Message keys: hierarchical naming messages.commands.home.success
  • Placeholder system: {player}, {world}, {x}, {y}, {z} — with validation
  • Color code handling: legacy & vs MiniMessage <red> — when to use which
  • Multi-language support: resource bundle structure

Color & Component Standards:

  • Legacy ChatColor vs Adventure Component vs MiniMessage
  • Migration path: ChatColor.translateAlternateColorCodes('&', msg) → MiniMessage equivalent
  • Audience API usage: player.sendMessage(Component)
  • Gradient support, hover events, click events in modern Paper

8. Common AI Polish Failures (30+ Examples)

For EACH failure, show:

  1. What AI typically generates (BAD)
  2. Why it's unprofessional or buggy
  3. The corrected version (GOOD)
  4. The prompt engineering fix (what to tell AI to avoid this)

Formatting Issues (10 examples):

  1. Mixes tabs and spaces (or uses 2-space then 4-space indentation)
  2. 200+ character lines
  3. Missing braces on single-line if-statements
  4. Inconsistent brace style (Egyptian vs Allman in same file)
  5. Missing spaces around operators (a=b vs a = b)
  6. No blank lines between logical sections
  7. Imports scattered randomly (not grouped)
  8. Wildcard imports in production code
  9. Trailing whitespace / inconsistent final newlines
  10. Inconsistent indentation in multi-line method calls

Naming Inconsistencies (5 examples):

  1. Class PlayerManager but method handlePlayerData() — verb/noun mismatch
  2. Field config in one class, cfg in another, configuration in third
  3. Hungarian notation mixed with modern naming (strPlayerName vs playerName)
  4. Method getPlayers() returns List<String> but getOnlinePlayers() returns Collection<Player> — inconsistent return types
  5. Constants defined as static final int maxPlayers (not UPPER_SNAKE_CASE)

Logic Red Flags (10 examples):

  1. Nests if-statements 6 levels deep instead of using early returns
  2. Uses // TODO or // FIXME as permanent solutions
  3. Commented-out code blocks left in production
  4. Magic numbers (if (args.length < 3)) without named constants
  5. Creates unused variables and methods (dead code)
  6. Catches generic Exception instead of specific exceptions
  7. Swallows exceptions with empty catch blocks
  8. Uses == instead of .equals() for String comparison
  9. Public fields instead of private fields with getters
  10. Raw types (ArrayList instead of ArrayList<Player>)

Performance Style Issues (3 examples):

  1. String concatenation in loops instead of StringBuilder
  2. new Location(world, x, y, z) in hot event handlers instead of caching
  3. getOnlinePlayers() array creation every tick

Security Style Issues (2 examples):

  1. String concatenation for SQL queries (even in "utility" methods)
  2. No input validation on command arguments

Output Instructions

CRITICAL: Generate as a complete downloadable file.

Format as professional Markdown:

  • Code blocks with java language tags for ALL examples
  • Tables for convention comparisons
  • Bold for critical rules (non-negotiable)
  • inline code for API references and names
  • > Warning: callout blocks for red flags
  • > AI Prevention: callout blocks with exact prompt phrases
  • [ ] checklists for actionable items

Target length: 18,000+ words — a true reference, not a blog post. Every section fully expanded with real code.

Output the COMPLETE document at the end so I can save it as a file.

This guide will be used in every code review. Make it comprehensive enough that code quality issues are caught before commit.

Kodari AI
KodariMay 30 at 3:35 pm 40
PluginQualityGuide
A comprehensive Minecraft plugin code quality and polish standards reference guide. Covers naming conventions, code organization, documentation standards, error handling, resource management, plugin lifecycle discipline, configuration standards, and 30+ common AI code generation failures with corrections. Designed as a production-ready checklist for Paper 1.21.4 plugin development teams.

Plugin_Code_Quality_Standards.md — complete reference guide generated. Here’s what’s inside:

~19,000 words across 8 sections + 4 appendices:

  • §1 Naming Conventions — Every class type (main, manager, listener, command, utility, API, exception), method patterns, field naming, constants, and packages. Each with convention table, AI mistake, corrected version, and edge cases.

  • §2 Code Organization — The 50-line rule with thresholds by method type, import policy, annotation discipline, brace style, and SRP with real plugin examples.

  • §3 Documentation — MUST/SHOULD/OPTIONAL Javadoc matrix, self-documenting code vs comments (with smell detection), plugin.yml standards, and config.yml documentation format.

  • §4 Error Handling — Exception hierarchy design, try-catch placement, the empty catch block treatment, logging levels table, and null safety patterns with the right tool for each scenario.

  • §5 Resource Management — Complete JDBC try-with-resources pattern, listener lifecycle with dynamic listener example, per-player task tracking, and connection pool rules.

  • §6 Plugin Lifecycle — onEnable() initialization order, what doesn’t belong (with async alternatives), onDisable() checklist, onLoad() guidance, and reload-safe architecture.

  • §7 Config & Messaging — Typed config wrapper pattern, message externalization with MessageManager implementation, Adventure vs legacy color codes, and fail-fast validation.

  • §8 AI Failures — 30 documented failures across formatting (10), naming (5), logic (10), performance (3), and security (2). Each with BAD code, explanation, GOOD code, and exact prompt phrase.

  • Appendix A — 30-point pre-commit checklist organized by category.

  • Appendix B — Visual scanning guide: instant rejections, requires explanation, style warnings, architecture smells.

  • Appendix C — Master quality block (copy-paste prompt prefix) + targeted phrases by problem type.

  • Appendix D — IntelliJ settings, .editorconfig, Checkstyle XML config, and VSCode settings.

Kodari can make mistakes. Review important code before using.
Files
Plugin_Code_Quality_Standards.md
Code
1 3,258
Plugin_Code_Quality_Standards.md
# Minecraft Plugin Code Quality & Polish Standards
## Paper 1.21.4 — Production-Ready Code Review Checklist

> This document is a living reference for plugin developers and code reviewers. Every rule here exists because real production plugins have broken in real servers due to violations of these principles. Read it once, then keep it open during every review.

---

## Table of Contents

1. [Naming Conventions](#1-naming-conventions)
2. [Code Organization & Readability](#2-code-organization--readability)
3. [Documentation Standards](#3-documentation-standards)
4. [Error Handling Elegance](#4-error-handling-elegance)
5. [Resource Management](#5-resource-management)
6. [Plugin Lifecycle Discipline](#6-plugin-lifecycle-discipline)
7. [Configuration & Messaging Standards](#7-configuration--messaging-standards)
8. [Common AI Polish Failures](#8-common-ai-polish-failures-30-examples)
9. [Appendix A: 30-Point Pre-Commit Checklist](#appendix-a-30-point-pre-commit-checklist)
10. [Appendix B: Code Review Red Flags](#appendix-b-code-review-red-flags-visual-scanning-guide)
11. [Appendix C: AI Prompt Engineering Phrases](#appendix-c-ai-prompt-engineering-phrases-for-better-output)
12. [Appendix D: Auto-Format Configuration](#appendix-d-auto-format-configuration)

---

## 1. Naming Conventions

Naming is the single highest-leverage quality investment in any codebase. A well-named class or method communicates intent without requiring the reader to open the implementation. Poor naming forces every reviewer, every future maintainer, and every AI tool to guess — and guessing introduces bugs.

---

### 1.1 Class Naming Strategy

#### Main Plugin Class

**Rule:** The main class should be named exactly after the plugin, in PascalCase, with no suffix.

| Pattern | Verdict | Reason |
|---|---|---|
| `MyPlugin` | ✅ Correct | Clean, unambiguous, matches plugin name |
| `MyPluginPlugin` | ❌ Wrong | Redundant suffix, reads awkwardly |
| `MyPluginMain` | ❌ Wrong | "Main" is an implementation detail, not a concept |
| `Main` | ❌ Wrong | Completely non-descriptive, conflicts with Java convention |
| `PluginCore` | ❌ Wrong | Vague, doesn't identify the plugin |

**Why it matters:** The main class is the entry point that other plugins reference via `JavaPlugin.getPlugin(MyPlugin.class)`. If it's named `MyPluginMain`, every external reference looks like `JavaPlugin.getPlugin(MyPluginMain.class)` — which is confusing and inconsistent with the plugin's identity.

**Common AI mistake:**
```java
// AI often generates this
public class MyPluginMain extends JavaPlugin {
    private static MyPluginMain instance;
```

**Corrected version:**
```java
// Correct
public class MyPlugin extends JavaPlugin {
    private static MyPlugin instance;
```

**Edge case:** If your plugin name is a reserved Java keyword or conflicts with a Bukkit class (unlikely but possible), append `Plugin` as a last resort. Document why.

---

#### Manager Classes

**Rule:** Use the `Manager` suffix for classes that own and coordinate a domain's lifecycle. Use `Service` for stateless operation classes. Use `Repository` for data access classes.

| Suffix | When to Use | Example |
|---|---|---|
| `Manager` | Owns lifecycle, holds state, coordinates subsystems | `PlayerDataManager`, `ArenaManager` |
| `Service` | Stateless operations, business logic, no lifecycle | `EconomyService`, `PermissionService` |
| `Repository` | Data access only — reads/writes to storage | `PlayerRepository`, `ShopRepository` |
| `Handler` | Processes a single type of event or request | `ChatHandler`, `PaymentHandler` |
| `Factory` | Creates instances of complex objects | `ItemFactory`, `ArenaFactory` |

**Why it matters:** When a class is named `PlayerManager`, a reviewer immediately knows it holds a `Map<UUID, PlayerData>` and has `load()`, `save()`, `get()`, and `remove()` methods. When it's named `PlayerUtils`, the reviewer has no idea what to expect.

**Common AI mistake:**
```java
// AI conflates all three concepts into one class
public class PlayerUtils {
    private Map<UUID, PlayerData> players = new HashMap<>();
    
    public void saveToDatabase(PlayerData data) { ... }
    public PlayerData loadFromDatabase(UUID uuid) { ... }
    public void giveReward(Player player) { ... }
    public String formatName(Player player) { ... }
}
```

**Corrected version:**
```java
// Split by responsibility
public class PlayerDataManager {          // owns lifecycle
    private final Map<UUID, PlayerData> cache = new HashMap<>();
}

public class PlayerRepository {           // data access only
    public void save(PlayerData data) { ... }
    public PlayerData load(UUID uuid) { ... }
}

public class PlayerService {              // business logic
    public void giveReward(Player player) { ... }
}

public class PlayerFormatter {            // pure utility
    public static String formatName(Player player) { ... }
}
```

---

#### Listener Classes

**Rule:** Name listeners after the domain they cover, not the specific event. Group related events into one listener class.

| Pattern | Verdict | Reason |
|---|---|---|
| `PlayerJoinListener` | ⚠️ Acceptable for small plugins | Fine if only one join-related event |
| `PlayerListener` | ✅ Preferred | Groups all player-related events |
| `CombatListener` | ✅ Preferred | Groups all combat events |
| `EventListener` | ❌ Wrong | Completely non-descriptive |
| `Listeners` | ❌ Wrong | Plural class names are a code smell |

**Why it matters:** If you have `PlayerJoinListener`, `PlayerQuitListener`, `PlayerMoveListener`, and `PlayerChatListener` as four separate classes, you have four files to open to understand player behavior. Group them into `PlayerListener` and the domain is self-contained.

**Exception:** If a listener class exceeds ~150 lines, split it. A `CombatListener` handling 15 different combat events is too large — split into `MeleeCombatListener` and `ProjectileCombatListener`.

**Common AI mistake:**
```java
// AI creates one listener per event
public class OnPlayerJoinListener implements Listener { ... }
public class OnPlayerQuitListener implements Listener { ... }
public class OnPlayerDeathListener implements Listener { ... }
```

**Corrected version:**
```java
// Group by domain
public class PlayerLifecycleListener implements Listener {
    @EventHandler public void onJoin(PlayerJoinEvent event) { ... }
    @EventHandler public void onQuit(PlayerQuitEvent event) { ... }
    @EventHandler public void onDeath(PlayerDeathEvent event) { ... }
}
```

---

#### Command Classes

**Rule:** Use the `Command` suffix, not prefix. Name after the command's action.

| Pattern | Verdict | Reason |
|---|---|---|
| `ReloadCommand` | ✅ Correct | Noun-first, action-second, sorts alphabetically by domain |
| `HomeCommand` | ✅ Correct | Clear, concise |
| `CommandReload` | ❌ Wrong | Prefix convention makes alphabetical sorting useless |
| `ReloadCmd` | ❌ Wrong | Abbreviations reduce readability |
| `ReloadCommandExecutor` | ❌ Wrong | Redundant — it's obviously an executor |

**Why it matters:** In a plugin with 20 commands, `Command`-prefixed classes sort as `CommandBan`, `CommandHome`, `CommandKick` — all together, not grouped by domain. `BanCommand`, `HomeCommand`, `KickCommand` sort by domain, which is how developers think about them.

**Common AI mistake:**
```java
public class CommandHandler implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        if (cmd.getName().equalsIgnoreCase("home")) { ... }
        if (cmd.getName().equalsIgnoreCase("sethome")) { ... }
        if (cmd.getName().equalsIgnoreCase("delhome")) { ... }
        // 300 more lines
    }
}
```

**Corrected version:**
```java
// One class per command
public class HomeCommand implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { ... }
}

public class SetHomeCommand implements CommandExecutor { ... }
public class DeleteHomeCommand implements CommandExecutor { ... }
```

---

#### Utility Classes

**Rule:** Static utility classes are acceptable only when the methods are truly stateless, domain-agnostic, and reusable across the entire plugin. Name them `[Domain]Utils` or `[Domain]Helper`.

| Pattern | Verdict | Reason |
|---|---|---|
| `StringUtils` | ✅ Correct | Domain-specific, clear scope |
| `ItemUtils` | ✅ Correct | Clear what it operates on |
| `Utils` | ❌ Wrong | Becomes a dumping ground for everything |