java-best-practices-code-review
Analyzes Java code against industry best practices and evaluates design principles including SOLID, exception handling, thread safety, and resource management. Reviews naming conventions, Stream API usage, Optional patterns, and general code quality. Use when reviewing Java files, checking code quality, evaluating exception handling, or auditing resource management.
What this skill does
Works with .java files, Spring components, and Java projects of any size.
# Java Code Review
## Table of Contents
- [Purpose](#purpose)
- [When to Use](#when-to-use)
- [Quick Start](#quick-start)
- [Instructions](#instructions)
- [Examples](#examples)
- [Requirements](#requirements)
- [Review Checklist](#review-checklist)
- [Output Format](#output-format)
- [Error Handling](#error-handling)
## Purpose
Performs comprehensive code reviews of Java code against industry best practices, SOLID principles, and modern Java idioms. Provides actionable feedback to improve code quality, maintainability, and security.
## When to Use
Use this skill when you need to:
- Review Java files for code quality issues
- Analyze SOLID principle compliance
- Evaluate exception handling patterns
- Assess thread safety in concurrent code
- Audit resource management (try-with-resources usage)
- Check naming conventions and coding standards
- Review Stream API and Optional usage
- Verify modern Java features adoption (Java 8+ idioms)
- Conduct PR reviews for Java projects
- Identify refactoring opportunities
## Quick Start
Point to any Java file or directory and receive immediate feedback on code quality issues:
```bash
# Review a single file
Review src/main/java/com/example/UserService.java
# Review all Java files in a package
Review all Java files in src/main/java/com/example/service/
```
## Instructions
### Step 1: Identify Target Scope
Determine what needs to be reviewed:
- Single Java class file
- Package directory (all .java files)
- Specific component type (controllers, services, repositories)
- Entire src tree
Use Glob to find Java files if not explicitly specified:
```bash
**/*.java # All Java files
src/main/java/**/*Service.java # All service classes
```
### Step 2: Read and Analyze Code
For each Java file, perform multi-dimensional analysis:
**SOLID Principles Assessment:**
- Single Responsibility: Does class have one clear purpose?
- Open/Closed: Is class extensible without modification?
- Liskov Substitution: Are inheritance hierarchies sound?
- Interface Segregation: Are interfaces focused and minimal?
- Dependency Inversion: Does code depend on abstractions?
**Code Quality Checks:**
- Naming conventions (camelCase, PascalCase, UPPER_SNAKE_CASE)
- Method length (flag methods over 50 lines)
- Class cohesion (related methods grouped together)
- Magic numbers and strings (should be constants)
- Code duplication (DRY principle violations)
**Exception Handling:**
- Proper exception types (checked vs unchecked)
- No empty catch blocks
- No catching generic Exception unless necessary
- Meaningful error messages
- Proper exception chaining (throw new CustomException(e))
**Resource Management:**
- try-with-resources for AutoCloseable resources
- Proper Stream/File/Connection closing
- No resource leaks
**Modern Java Patterns:**
- Stream API usage (prefer streams over loops where appropriate)
- Optional instead of null returns
- Records for data classes (Java 14+)
- Switch expressions (Java 14+)
- Text blocks for multi-line strings (Java 15+)
**Thread Safety:**
- Proper synchronization if needed
- Immutability where possible
- Thread-safe collection usage
- Avoid shared mutable state
**Security Concerns:**
- No hardcoded credentials
- Proper input validation
- SQL injection prevention (use PreparedStatement)
- Path traversal vulnerabilities
- Sensitive data logging
### Step 3: Generate Structured Review Report
Organize findings by severity:
**CRITICAL** - Must fix immediately:
- Security vulnerabilities
- Resource leaks
- Thread safety violations in concurrent code
**HIGH** - Should fix soon:
- SOLID principle violations
- Poor error handling
- Significant code smells
**MEDIUM** - Improve when possible:
- Code duplication
- Naming convention issues
- Missing modern Java features
**LOW** - Nice to have:
- Code style inconsistencies
- Minor optimizations
- Documentation improvements
### Step 4: Provide Actionable Recommendations
For each issue identified:
1. Specify exact location (file, line number)
2. Explain the problem clearly
3. Show code example of the issue
4. Provide corrected code example
5. Explain why the change improves code quality
## Examples
### Example 1: Review Single Service Class
**Input:**
```java
public class UserService {
private UserRepository userRepository = new UserRepository();
public User getUser(String id) {
User user = userRepository.findById(id);
if (user == null) {
return null;
}
return user;
}
}
```
**Review Output:**
```
CRITICAL Issues:
- Line 2: Dependency Inversion violation - direct instantiation of UserRepository
Fix: Inject UserRepository via constructor
HIGH Issues:
- Line 7: Returns null instead of Optional<User>
Fix: Return Optional.ofNullable(user)
MEDIUM Issues:
- Class lacks @Service annotation (assuming Spring)
- No logging for diagnostic purposes
Recommended Refactoring:
```java
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private static final Logger log = LoggerFactory.getLogger(UserService.class);
public Optional<User> getUser(String id) {
log.debug("Fetching user with id: {}", id);
return Optional.ofNullable(userRepository.findById(id));
}
}
```
```
### Example 2: Review Controller with Multiple Issues
**Input:**
```java
public class UserController {
@GetMapping("/users/{id}")
public User getUser(@PathVariable String id) {
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/db", "root", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE id = " + id);
if (rs.next()) {
return new User(rs.getString("name"), rs.getString("email"));
}
} catch (Exception e) {
// ignore
}
return null;
}
}
```
**Review Output:**
```
CRITICAL Issues:
1. Line 7: SQL Injection vulnerability - concatenating user input into query
Fix: Use PreparedStatement with parameters
2. Line 5: Hardcoded database credentials in code
Fix: Externalize to application.properties and use Spring's DataSource
3. Lines 5-10: Resource leak - Connection, Statement, ResultSet not closed
Fix: Use try-with-resources or Spring JdbcTemplate
4. Line 11-13: Empty catch block silently swallows exceptions
Fix: Log exception and throw appropriate response exception
HIGH Issues:
5. Architecture violation: Controller directly accessing database
Fix: Use Service layer and Repository pattern
6. Line 14: Returns null instead of proper HTTP 404
Fix: Throw ResponseStatusException or return ResponseEntity
MEDIUM Issues:
7. Missing @RestController annotation
8. No input validation on id parameter
9. No API documentation (@Operation, @ApiResponse)
Recommended Architecture:
```java
@RestController
@RequiredArgsConstructor
@Validated
public class UserController {
private final UserService userService;
@GetMapping("/users/{id}")
@Operation(summary = "Get user by ID")
public ResponseEntity<User> getUser(
@PathVariable @NotBlank String id) {
return userService.getUser(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
}
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
public Optional<User> getUser(String id) {
return userRepository.findById(id);
}
}
@Repository
public interface UserRepository extends JpaRepository<User, String> {
}
```
```
### Example 3: Review Stream API Usage
**Input:**
```java
List<String> activeUserNames = new ArrayList<>();
for (User user : users) {
if (user.isActive()) {
activeUserNames.add(user.getName());
}
}
Collections.sort(activeUserNames);
Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.