mirror of
https://github.com/github/awesome-copilot.git
synced 2026-02-22 11:25:13 +00:00
new java and springboot base best practices (#22)
* new java and springboot base best practices * Update java-and-springboot.md * Update java-and-springboot.md * split java and springboot instructions * header wrap with signle quote * remove duplicate instruction * address code reviews * apply update-readme script * java and kotlin prompts for springboot * apply update-readme script * Apply suggestion from @aaronpowell --------- Co-authored-by: Aaron Powell <me@aaron-powell.com>
This commit is contained in:
64
instructions/java.instructions.md
Normal file
64
instructions/java.instructions.md
Normal file
@@ -0,0 +1,64 @@
|
||||
---
|
||||
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<T>` 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 |
|
||||
| ------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
|
||||
| `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. |
|
||||
| `S1188` | Catch blocks should not be empty | Always log or handle exceptions meaningfully. |
|
||||
|
||||
## 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.
|
||||
58
instructions/springboot.instructions.md
Normal file
58
instructions/springboot.instructions.md
Normal file
@@ -0,0 +1,58 @@
|
||||
---
|
||||
description: 'Guidelines for building Spring Boot base applications'
|
||||
applyTo: '**/*.java, **/*.kt'
|
||||
---
|
||||
|
||||
# Spring Boot Development
|
||||
|
||||
## General Instructions
|
||||
|
||||
- Make only high confidence suggestions when reviewing code changes.
|
||||
- Write code with good maintainability practices, including comments on why certain design decisions were made.
|
||||
- Handle edge cases and write clear exception handling.
|
||||
- For libraries or external dependencies, mention their usage and purpose in comments.
|
||||
|
||||
## Spring Boot Instructions
|
||||
|
||||
### Dependency Injection
|
||||
|
||||
- Use constructor injection for all required dependencies.
|
||||
- Declare dependency fields as `private final`.
|
||||
|
||||
### Configuration
|
||||
|
||||
- Use YAML files (`application.yml`) for externalized configuration.
|
||||
- Environment Profiles: Use Spring profiles for different environments (dev, test, prod)
|
||||
- Configuration Properties: Use @ConfigurationProperties for type-safe configuration binding
|
||||
- Secrets Management: Externalize secrets using environment variables or secret management systems
|
||||
|
||||
### Code Organization
|
||||
|
||||
- Package Structure: Organize by feature/domain rather than by layer
|
||||
- Separation of Concerns: Keep controllers thin, services focused, and repositories simple
|
||||
- Utility Classes: Make utility classes final with private constructors
|
||||
|
||||
### Service Layer
|
||||
|
||||
- Place business logic in `@Service`-annotated classes.
|
||||
- Services should be stateless and testable.
|
||||
- Inject repositories via the constructor.
|
||||
- Service method signatures should use domain IDs or DTOs, not expose repository entities directly unless necessary.
|
||||
|
||||
### Logging
|
||||
|
||||
- Use SLF4J for all logging (`private static final Logger logger = LoggerFactory.getLogger(MyClass.class);`).
|
||||
- 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.
|
||||
- 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.
|
||||
Reference in New Issue
Block a user