Java Standards
Java Standards
Section titled “Java Standards”1. Build System
Section titled “1. Build System”- Tool:
MavenorGradle. Prefer Gradle for modern projects. - Version: Java 17+ (LTS). Use
--enable-previewonly for evaluation. - Dependencies: Declare in
pom.xmlorbuild.gradle. Use dependency management BOMs.
2. Code Style
Section titled “2. Code Style”- Formatter:
google-java-formatorpalantir-java-format. Line length 120. - Linter:
checkstyle,spotbugs,error-prone. - Type Checker: Compiler strict warnings enabled. Use
@Nullable/@NonNullannotations.
Gradle Configuration
Section titled “Gradle Configuration”java { toolchain { languageVersion = JavaLanguageVersion.of(17) }}
tasks.withType(JavaCompile) { options.compilerArgs += ['-Xlint:all', '-Werror']}3. Naming Conventions
Section titled “3. Naming Conventions”- Packages:
com.company.project.layer(lowercase, reverse domain) - Classes/Interfaces:
PascalCase - Methods/Variables:
camelCase - Constants:
UPPER_SNAKE_CASE - Private Fields:
camelCase(notm_or_prefix)
4. Project Structure
Section titled “4. Project Structure”src/├── main/│ ├── java/│ │ └── com/company/project/│ │ ├── domain/│ │ │ ├── entities/│ │ │ └── valueobjects/│ │ ├── application/│ │ │ ├── usecases/│ │ │ └── interfaces/│ │ └── infrastructure/│ │ └── persistence/│ └── resources/└── test/ └── java/ # Mirror main structure5. Class Design
Section titled “5. Class Design”- Immutability: Prefer immutable classes. Use
finalfields and builders. - Records: Use
record(Java 14+) for value objects and DTOs. - Sealed Classes: Use
sealedclasses (Java 17+) for restricted inheritance. - Interfaces: Define repository interfaces in application layer.
Example
Section titled “Example”public record Email(String value) { public Email { if (value == null || !value.matches("^[^@]+@[^@]+\\.[^@]+$")) { throw new IllegalArgumentException("Invalid email: " + value); } }}
public sealed interface Result<T> permits Success, Failure { // Sealed interface for result types}6. Dependency Injection
Section titled “6. Dependency Injection”- Framework: Use
SpringorGuicefor DI. Prefer constructor injection. - Configuration: Use
@Configurationclasses or@Beanmethods. - Scopes: Use
@Singletonfor stateless services. Avoid@RequestScopein domain.
7. Testing
Section titled “7. Testing”- Framework:
JUnit 5withAssertJfor assertions. - Mocking:
Mockitofor mocks. Use@Mockand@InjectMocks. - Coverage:
JaCoCo. 95% is the absolute minimum for any module. Target 100% for domain, 95%+ for application and infrastructure.
Test Structure
Section titled “Test Structure”@ExtendWith(MockitoExtension.class)class UserServiceTest { @Mock private UserRepository userRepository;
@InjectMocks private UserService userService;
@Test void shouldCreateUserWithValidEmail() { // Given String email = "test@example.com";
// When User user = userService.createUser(email, "Test User");
// Then assertThat(user.getEmail()).isEqualTo(email); }}8. Error Handling
Section titled “8. Error Handling”- Custom Exceptions: Checked exceptions for recoverable errors, unchecked for programming errors.
- Domain Exceptions: Unchecked exceptions extending
RuntimeException. - Context: Include cause in exception constructor. Use
getMessage()for user-facing messages.
public class DomainException extends RuntimeException { public DomainException(String message) { super(message); }
public DomainException(String message, Throwable cause) { super(message, cause); }}9. Collections & Streams
Section titled “9. Collections & Streams”- Immutable Collections: Use
List.of(),Set.of(),Map.of()for immutable collections. - Streams: Prefer streams for transformations. Keep operations readable.
- Optional: Use
Optional<T>for nullable return values. AvoidOptionalin fields or parameters.
10. Annotations
Section titled “10. Annotations”- Null Safety: Use
@Nullableand@NonNull(JSR-305 or JetBrains). - Validation: Use
javax.validation(@NotNull,@Email,@Size). - Documentation: Use JavaDoc for public APIs. Include
@param,@return,@throws.
11. Dependencies
Section titled “11. Dependencies”Common Libraries
Section titled “Common Libraries”- HTTP:
OkHttp,Retrofit(REST clients) - Database:
JPA/Hibernate(ORM),JOOQ(type-safe SQL) - JSON:
JacksonorGson - Logging:
SLF4JwithLogback
12. Documentation
Section titled “12. Documentation”- JavaDoc: Required for all public classes, methods, and fields.
- Format: Use standard JavaDoc tags. Include examples for complex methods.
/** * Creates a new user with validated email address. * * @param email valid email address (must match RFC 5322) * @param name user's full name (non-null, non-empty) * @return new User entity instance * @throws InvalidEmailException if email format is invalid * @throws IllegalArgumentException if name is null or empty */public User createUser(String email, String name) { // Implementation}