From dd3224a13179fdf102e0ab52872f35f6d63deff7 Mon Sep 17 00:00:00 2001 From: Joseph Gonzales Date: Thu, 3 Jul 2025 22:15:05 +1200 Subject: [PATCH] split java and springboot instructions --- instructions/java.instructions.md | 69 +++++++++++++++++++ ...ringboot.md => springboot.instructions.md} | 30 +++----- 2 files changed, 77 insertions(+), 22 deletions(-) create mode 100644 instructions/java.instructions.md rename instructions/{java-and-springboot.md => springboot.instructions.md} (57%) diff --git a/instructions/java.instructions.md b/instructions/java.instructions.md new file mode 100644 index 0000000..5ff5f43 --- /dev/null +++ b/instructions/java.instructions.md @@ -0,0 +1,69 @@ +--- +description: "Guidelines for building Java base applications" +applyTo: "**/*.java" +--- + +# Java Development + +## General Instructions + +- First, prompt the user if they want to integrate static analysis tools (SonarQube, PMD, Checkstyle) + into their project setup. If yes, provide guidance on tool selection and configuration. +- If the user declines static analysis tools or wants to proceed without them, continue with implementing the Best practices, bug patterns and code smell prevention guidelines outlined below. +- Address code smells proactively during development rather than accumulating technical debt. +- Focus on readability, maintainability, and performance when refactoring identified issues. +- Use IDE / Code editor reported warnings and suggestions to catch common patterns early in development. + +## Best practices + +- **Records**: For classes primarily intended to store data (e.g., DTOs, immutable data structures), **Java Records should be used instead of traditional classes**. +- **Pattern Matching**: Utilize pattern matching for `instanceof` and `switch` expression to simplify conditional logic and type casting. +- **Type Inference**: Use `var` for local variable declarations to improve readability, but only when the type is explicitly clear from the right-hand side of the expression. +- **Immutability**: Favor immutable objects. Make classes and fields `final` where possible. Use collections from `List.of()`/`Map.of()` for fixed data. Use `Stream.toList()` to create immutable lists. +- **Streams and Lambdas**: Use the Streams API and lambda expressions for collection processing. Employ method references (e.g., `stream.map(Foo::toBar)`). +- **Null Handling**: Avoid returning or accepting `null`. Use `Optional` for possibly-absent values and `Objects` utility methods like `equals()` and `requireNonNull()`. + +### Naming Conventions + +- Follow Google's Java style guide: + - `UpperCamelCase` for class and interface names. + - `lowerCamelCase` for method and variable names. + - `UPPER_SNAKE_CASE` for constants. + - `lowercase` for package names. +- Use nouns for classes (`UserService`) and verbs for methods (`getUserById`). +- Avoid abbreviations and Hungarian notation. + +### Bug Patterns + +| Rule ID | Description | Example / Notes | +| ------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | +| `S2259` | Null pointers should not be dereferenced | Avoid calling methods on objects that may be null. Use `Objects.requireNonNull()` or `Optional`. | +| `S2095` | Resources should be closed | Use try-with-resources when working with streams, files, sockets, etc. | +| `S1698` | Objects should be compared with `.equals()` instead of `==` | Especially important for Strings and boxed primitives. | +| `S1905` | Redundant casts should be removed | Clean up unnecessary or unsafe casts. | +| `S3518` | Conditions should not always evaluate to true or false | Watch for infinite loops or if-conditions that never change. | +| `S108` | Unreachable code should be removed | Code after `return`, `throw`, etc., must be cleaned up. | + +--- + +### Code Smells + +| Rule ID | Description | Example / Notes | +| ------- | ------------------------------------------------------ | ----------------------------------------------------------------------------- | +| `S107` | Methods should not have too many parameters | Refactor into helper classes or use builder pattern. | +| `S121` | Duplicated blocks of code should be removed | Consolidate logic into shared methods. | +| `S138` | Methods should not be too long | Break complex logic into smaller, testable units. | +| `S3776` | Cognitive complexity should be reduced | Simplify nested logic, extract methods, avoid deep `if` trees. | +| `S1192` | String literals should not be duplicated | Replace with constants or enums. | +| `S1854` | Unused assignments should be removed | Avoid dead variables—remove or refactor. | +| `S109` | Magic numbers should be replaced with constants | Improves readability and maintainability. | +| `S100` | Naming conventions should be consistent | Use `lowerCamelCase`, `UpperCamelCase`, or `UPPER_SNAKE_CASE` as appropriate. | +| `S1188` | Catch blocks should not be empty | Always log or handle exceptions meaningfully. | +| `S2629` | Logging statements should not use string concatenation | Use parameterized logging (e.g., `logger.info("Result: {}", result)`). | + +## Build and Verification + +- After adding or modifying code, verify the project continues to build successfully. +- If the project uses Maven, run `mvn clean install`. +- If the project uses Gradle, run `./gradlew build` (or `gradlew.bat build` on Windows). +- Ensure all tests pass as part of the build. diff --git a/instructions/java-and-springboot.md b/instructions/springboot.instructions.md similarity index 57% rename from instructions/java-and-springboot.md rename to instructions/springboot.instructions.md index fc2152e..edc9460 100644 --- a/instructions/java-and-springboot.md +++ b/instructions/springboot.instructions.md @@ -1,9 +1,9 @@ --- -description: 'Guidelines for building Java and Springboot base applications' -applyTo: '**/*.java' +description: "Guidelines for building Springboot base applications" +applyTo: "**/*.java, **/*.kt," --- -# Java and Spring Boot Development +# Spring Boot Development ## General Instructions @@ -12,25 +12,6 @@ applyTo: '**/*.java' - Handle edge cases and write clear exception handling. - For libraries or external dependencies, mention their usage and purpose in comments. -## Java Instructions - -- **Records**: For classes primarily intended to store data (e.g., DTOs, immutable data structures), **Java Records should be used instead of traditional classes**. -- **Pattern Matching**: Utilize pattern matching for `instanceof` and `switch` expression to simplify conditional logic and type casting. -- **Type Inference**: Use `var` for local variable declarations to improve readability, but only when the type is explicitly clear from the right-hand side of the expression. -- **Immutability**: Favor immutable objects. Make classes and fields `final` where possible. Use collections from `List.of()`/`Map.of()` for fixed data. Use `Stream.toList()` to create immutable lists. -- **Streams and Lambdas**: Use the Streams API and lambda expressions for collection processing. Employ method references (e.g., `stream.map(Foo::toBar)`). -- **Null Handling**: Avoid returning or accepting `null`. Use `Optional` for possibly-absent values and `Objects` utility methods like `equals()` and `requireNonNull()`. - -## Naming Conventions - -- Follow Google's Java style guide: - - `UpperCamelCase` for class and interface names. - - `lowerCamelCase` for method and variable names. - - `UPPER_SNAKE_CASE` for constants. - - `lowercase` for package names. -- Use nouns for classes (`UserService`) and verbs for methods (`getUserById`). -- Avoid abbreviations and Hungarian notation. - ## Spring Boot Instructions ### Dependency Injection @@ -64,6 +45,11 @@ applyTo: '**/*.java' - Do not use concrete implementations (Logback, Log4j2) or `System.out.println()` directly. - Use parameterized logging: `logger.info("User {} logged in", userId);`. +### Security & Input Handling + +- Use parameterized queries | Always use Spring Data JPA or `NamedParameterJdbcTemplate` to prevent SQL injection. +- Validate request bodies and parameters using JSR-380 (`@NotNull`, `@Size`, etc.) annotations and `BindingResult` + ## Build and Verification - After adding or modifying code, verify the project continues to build successfully.