Skip to main content

java-best-practices

Opinionated modern Java (21+) coding best practices, style guides, and anti-patterns. Curated by VirtusLab engineers. Covers code style, null safety, error handling, immutability, testing, concurrency, and tooling.

Quellinformationen

Repository
VirtusLab/agent-skills
Letzte Quellaktivität
5. März 2026 um 09:57
Erkannte Sprache von SKILL.md
Englisch
Sterne
7
Forks
1

Installationsoptionen

Standardmäßig ist der Prompt ausgewählt, der zuerst die Quelle prüft. Sie können zu einem direkten Befehl wechseln oder eine lokale Kopie herunterladen.

Quelldateien prüfen

Lesen Sie SKILL.md und alle von SkillsMP angezeigten Begleitdateien, bevor Sie sich für eine Installation entscheiden.

Datei-Explorer
2 Dateien

SKILL.md wird angezeigt

SKILL.md
Quellanweisungen · Schreibgeschützte Vorschau
name
java-best-practices
description
Opinionated modern Java (21+) coding best practices, style guides, and anti-patterns. Curated by VirtusLab engineers. Covers code style, null safety, error handling, immutability, testing, concurrency, and tooling.
# Java Best Practices by VirtusLab Opinionated, modern Java skill. Targets Java 21+ and explicitly cuts off outdated patterns. When writing or reviewing Java code, follow these guidelines strictly. ## Core Philosophy - **Composed Method Pattern** is the single most impactful practice in Java. Every method should do one thing, at one level of abstraction, and be short enough to read in one glance. This pattern alone transforms unreadable code into clean code. - **Effective Java by Joshua Bloch** remains the authoritative reference. Its principles are still current. When in doubt, consult it. - **Use library code.** Do not reimplement what the standard library or a well-established library already provides. This is one of the most violated and most impactful principles. - **Composition over inheritance.** Always. Use interfaces with default methods and delegation instead of deep class hierarchies. - **GRASP principles** (General Responsibility Assignment Software Patterns) guide object-oriented design: Information Expert, Creator, Controller, Low Coupling, High Cohesion, Polymorphism, Pure Fabrication, Indirection, Protected Variations. ## Modern Java (21+) — Use These Features Use modern Java features aggressively. Do not write pre-Java 17 style code. ### Records for Data Objects Use `record` for all immutable data carriers. Do NOT use Lombok `@Value`, `@Data`, `@Getter`, or hand-written POJOs for data objects. ```java // WRONG — legacy style @Value public class User { String username; String email; } // WRONG — hand-written boilerplate public class User { private final String username; private final String email; // constructor, getters, equals, hashCode, toString... } // CORRECT public record User(String username, String email) {} ``` Lombok is acceptable **only** for `@Builder` on non-record classes where the builder pattern is genuinely needed. For everything else, use records or plain Java. ### Sealed Classes for Domain Modeling (ADTs) Use `sealed` classes and interfaces to model algebraic data types. This gives exhaustiveness checking in `switch` expressions. ```java public sealed interface PaymentResult permits PaymentSuccess, PaymentFailure, PaymentPending { } public record PaymentSuccess(String transactionId, Money amount) implements PaymentResult {} public record PaymentFailure(String reason, ErrorCode code) implements PaymentResult {} public record PaymentPending(String transactionId) implements PaymentResult {} ``` ### Switch Expressions with Pattern Matching Use switch expressions (not statements) with pattern matching. Prefer exhaustive switches. ```java // CORRECT String message = switch (result) { case PaymentSuccess success -> "Paid %s".formatted(success.amount()); case PaymentFailure failure -> "Failed: %s".formatted(failure.reason()); case PaymentPending pending -> "Pending: %s".formatted(pending.transactionId()); }; // WRONG — old-style switch statement with break switch (result.getType()) { case SUCCESS: message = "Paid"; break; // ... } ``` ### Null Handling Inside `switch` (Java 21+) ```java // CORRECT — null is an explicit case return switch (status) { case null -> "unknown"; case ACTIVE -> "active"; case PAUSED -> "paused"; }; // WRONG — null handled outside the switch if (status == null) return "unknown"; return switch (status) { case ACTIVE -> "active"; case PAUSED -> "paused"; }; ``` ### Pattern Matching for `instanceof` ```java // CORRECT if (obj instanceof String s && !s.isBlank()) { process(s); } // WRONG if (obj instanceof String) { String s = (String) obj; process(s); } ``` ### Text Blocks Use text blocks for multi-line strings (SQL, JSON, HTML, etc.). ```java String query = """ SELECT u.id, u.name FROM users u WHERE u.active = true ORDER BY u.name """; ``` ### `var` for Local Variables Use `var` for local variables when the type is obvious from the right-hand side. Do not use `var` when it reduces readability. ```java // CORRECT — type is obvious var users = userRepository.findAll(); var mapper = new ObjectMapper(); // WRONG — type is not obvious, use explicit type var result = process(data); ``` ### Record Patterns (Java 21) Destructure records directly in `instanceof` and `switch` expressions. ```java // CORRECT if (obj instanceof Point(int x, int y)) { System.out.println(x + ", " + y); } String desc = switch (shape) { case Circle(double r) -> "Circle r=" + r; case Rect(double w, double h) -> "Rect " + w + "x" + h; }; // WRONG — old style: cast + field access if (obj instanceof Point p) { System.out.println(p.x() + ", " + p.y()); } ``` ### Unnamed Variables (Java 22) Use `_` for unused variables, catch parameters, and lambda parameters. ```java // CORRECT try { ... } catch (Exception _) { ... } try (var _ = ScopedValue.where(KEY, value)) { ... } list.stream().map(_ -> "constant").toList(); // WRONG try { ... } catch (Exception ignored) { ... } try { ... } catch (Exception e) { ... } // when e is never used ``` ### Immutable Collections Use factory methods for immutable collections. Never use `Arrays.asList()` or `new ArrayList<>()` for fixed collections. ```java // CORRECT var roles = List.of("ADMIN", "USER"); var config = Map.of("timeout", 30, "retries", 3); var tags = Set.of("java", "backend"); // WRONG var roles = Arrays.asList("ADMIN", "USER"); var roles = new ArrayList<>(List.of("ADMIN", "USER")); var roles = Collections.unmodifiableList(Arrays.asList("ADMIN", "USER")); ``` ### Sequenced Collections (Java 21) Use `getFirst()`, `getLast()`, `reversed()` instead of index arithmetic. ```java // CORRECT var first = list.getFirst(); var last = list.getLast(); var rev = list.reversed(); // WRONG var first = list.get(0); var last = list.get(list.size() - 1); var rev = new ArrayList<>(list); Collections.reverse(rev); ``` ### String Utilities (Java 11+) Use modern `String` methods. Do not reimplement what the standard library already provides. ```java // CORRECT str.isBlank() // replaces str.trim().isEmpty() str.strip() // Unicode-aware trim "ha".repeat(3) // "hahaha" "Hello %s".formatted(name) // replaces String.format(...) str.lines() // Stream<String> of lines // WRONG str.trim().isEmpty() String.format("Hello %s", name) ``` ## Null Safety **Nulls are not acceptable inside the system.** Things are non-null by default. Do not let nulls propagate beyond system boundaries (external APIs, database results, user input). - **Do NOT annotate everything with `@NonNull`** — that pollutes the code. Instead, treat everything as non-null by default. - **Use `@Nullable`** only when something genuinely can be null (rare, at system edges). - If you receive null from an external source, convert it at the boundary: to an `Optional`, a default value, or throw early. - **Never pass `null` as a method argument.** Never return `null` from a method. Use `Optional` for methods that may have no result. ```java // CORRECT — Optional for methods that may return nothing public Optional<User> findByEmail(String email) { return Optional.ofNullable(repository.get(email)); } // WRONG — returning null public User findByEmail(String email) { return repository.get(email); // might return null } ``` ## Optional - Use `Optional` as return type for public methods that may have no result. It communicates intent: "this method might return nothing, and you must handle it." - **Never** use `Optional` as a field type, method parameter, or in collections. - **Never** call `Optional.get()` without checking. Use `orElseThrow()`, `orElse()`, `map()`, `flatMap()`, `ifPresent()`. ```java // CORRECT userService.findByEmail(email) .map(User::username) .orElseThrow(() -> new UserNotFoundException(email)); // WRONG User user = userService.findByEmail(email).get(); ``` ## Error Handling **Use Java's exception mechanism.** Do not try to turn Java into Go or C with error return codes or `Result` wrapper types. Java has checked and unchecked exceptions — use them. - Use **unchecked exceptions** (extending `RuntimeException`) for programming errors and unexpected failures. - Use **checked exceptions** sparingly, only when the caller genuinely must handle the failure and there is a reasonable recovery path. - **Never swallow exceptions.** Always log or rethrow. - **Never catch `Exception` or `Throwable`** generically unless at the top-level error boundary (e.g., controller advice, global handler). - Use specific exception types. Create custom domain exceptions when the standard ones do not fit. - Use **multi-catch** to avoid duplicated catch blocks. ```java // CORRECT catch (IOException | SQLException e) { log.error("Data access failed", e); } // WRONG — duplicated handlers catch (IOException e) { log.error("...", e); } catch (SQLException e) { log.error("...", e); } ``` ```java // CORRECT public User getUser(UserId id) { return userRepository.findById(id) .orElseThrow(() -> new UserNotFoundException(id)); } // WRONG — returning null on error public User getUser(UserId id) { try { return userRepository.findById(id).orElse(null); } catch (Exception e) { return null; } } ``` ## Naming Conventions - **Classes**: `PascalCase` — nouns (`UserService`, `PaymentProcessor`). - **Methods**: `camelCase` — verbs (`findByEmail`, `processPayment`, `calculateTotal`). - **Variables**: `camelCase` — nouns (`userId`, `orderItems`). - **Constants**: `UPPER_SNAKE_CASE` (`MAX_RETRY_COUNT`, `DEFAULT_TIMEOUT`). - **Packages**: lowercase, dot-separated (`com.company.project.domain.user`). - **Booleans**: prefix with `is`, `has`, `should`, `can` (`isValid()`, `hasPermission()`, `shouldRetry()`). - **Collections**: plural names (`users`, `orders`, `products`). - **No abbreviations** in public APIs. `userRepository` not `userRepo`. `transactionManager` not `txMgr`. - Methods should not have surprising side effects. The name must accurately describe what the method does. ## Code Style & Formatting - Use **one consistent style** across the project: either standard Java Coding Conventions or IntelliJ defaults. The specific choice does not matter — consistency does. - Keep classes **package-private by default**. Only expose what is needed as `public`. - Apply `final` to variables when immutability is intended. - Use method references over lambdas when possible: `User::userId` instead of `u -> u.userId()`. - Organize imports: standard library, third-party, internal packages. No wildcard imports. - **If the project includes Spotless**, run the formatter after every code change (only for edited files). For Gradle: `./gradlew spotlessApply`. For Maven: `mvn spotless:apply`. ## Streams & Collections Use Java Streams for collection transformations. Prefer `filter()`, `map()`, `flatMap()`, `toList()`. ```java // CORRECT var activeEmails = users.stream() .filter(User::isActive) .map(User::email) .toList(); // WRONG — manual loop for simple transformation var activeEmails = new ArrayList<String>(); for (User user : users) { if (user.isActive()) { activeEmails.add(user.getEmail()); } } ``` Never perform side effects in intermediate operations (like `map`, `filter`, `flatMap`) — these should be pure functions. Terminal `forEach` is the right place for side effects. Prefer `Iterable.forEach()` over `stream().forEach()` when no intermediate operations are needed. ```java // WRONG — side effect in intermediate operation users.stream() .map(user -> { emailService.send(user); return user.email(); }) .toList(); // WRONG — unnecessary stream() when there is no pipeline users.stream().forEach(user -> emailService.send(user)); // CORRECT — Iterable.forEach for simple side effects users.forEach(user -> emailService.send(user)); // CORRECT — pure filter, side effect only in terminal forEach users.stream() .filter(User::isActive) .forEach(user -> emailService.send(user)); // CORRECT — plain loop when you need break/continue or checked exceptions for (var user : users) { emailService.send(user); } ``` ## Testing ### Consistent Test Naming Pick **one** naming convention for the entire project and enforce it. Recommended format: ``` methodName_shouldExpectedBehavior_whenCondition ``` Examples:
Auf GitHub ansehen
Diese SKILL.md ist sehr gross, daher zeigt SkillsMP hier nur den ersten Abschnitt. Auf GitHub ansehen