
public
Published on 7/10/2025
java-spring-boot-best-practice
Prompts
๐งฉ Java Development Rules
โ General Coding Standards
- Use meaningful and descriptive variable, method, and class names.
- Follow camelCase for variables and methods, PascalCase for classes.
- Avoid magic numbers and hardcoded values; use constants or enums.
- Keep methods short and focused on a single responsibility.
- Prefer composition over inheritance where applicable.
- Avoid deep nesting; use early returns to simplify logic.
๐งช Testing Best Practices
- Always write unit tests for public methods using JUnit 5.
- Use Mockito for mocking dependencies in unit tests.
- Follow AAA (Arrange-Act-Assert) pattern in tests.
- Ensure tests are independent and repeatable.
- Use parameterized tests for multiple input scenarios.
- Validate edge cases and exception handling in tests.
- Use integration tests for Spring Boot controllers and services.
๐ก๏ธ Defensive Programming
- Validate method inputs using
Objects.requireNonNull()or custom checks. - Use
Optionalto handle nullable return values safely. - Catch and log exceptions with meaningful messages.
- Avoid exposing internal implementation via public APIs.
- Use assertions only for development, not production logic.
- Handle external API failures gracefully with retries or fallbacks.
๐ Optimization & Modern Java Features
- Use
varfor local variables where type is obvious (Java 10+). - Prefer
switchexpressions over traditional switch (Java 14+). - Use
recordfor immutable data carriers (Java 14+). - Use
StreamAPI for collection processing, but avoid overuse. - Use
CompletableFuturefor async operations. - Use
Pattern Matching for instanceof(Java 16+) for cleaner type checks. - Use
Text Blocksfor multi-line strings (Java 15+). - Avoid unnecessary object creation; reuse where possible.
- Profile and benchmark critical code paths before optimizing.
๐ฑ Spring Boot Specific Rules
- Use constructor injection over field injection.
- Annotate configuration classes with
@Configuration. - Use
@Service,@Repository, and@Controllerappropriately. - Avoid business logic in controllers; delegate to services.
- Use
@Transactionalfor methods that modify data. - Externalize configuration using
application.ymlorapplication.properties. - Use
@Valueor@ConfigurationPropertiesfor config binding. - Validate request payloads using
@Validand@NotNull, etc. - Use pagination and filtering for large data sets.
- Secure endpoints using Spring Security best practices.