This document outlines the standards and best practices for Java development at Bayat.
- Follow the Google Java Style Guide with specific Bayat modifications noted in this document
- Use 4 spaces for indentation, not tabs
- Maximum line length should be 100 characters
- Files should be encoded in UTF-8
- Files should end with a newline
-
Classes and Interfaces:
- Use PascalCase (e.g.,
OrderProcessor
,CustomerRepository
) - Classes should be nouns
- Interfaces should be adjectives or nouns
- Generic types should use single uppercase letters (e.g.,
T
,E
,K
,V
)
- Use PascalCase (e.g.,
-
Methods:
- Use camelCase (e.g.,
processOrder()
,findCustomerById()
) - Methods should be verbs or verb phrases
- Test methods should be named descriptively (e.g.,
shouldThrowExceptionWhenInvalidInput()
)
- Use camelCase (e.g.,
-
Variables:
- Use camelCase (e.g.,
orderCount
,customerName
) - Constants should be UPPER_SNAKE_CASE (e.g.,
MAX_RETRY_COUNT
) - Boolean variables should use "is", "has", "can" prefixes (e.g.,
isValid
,hasPermission
)
- Use camelCase (e.g.,
-
Packages:
- Use lowercase, with hierarchical naming (e.g.,
io.bayat.module.submodule
) - Avoid underscores or other special characters
- Use lowercase, with hierarchical naming (e.g.,
-
Class Structure:
- Order of elements: static fields, instance fields, constructors, methods
- Public methods before protected and private methods
- Group related methods together
- Maximum class size should be 2000 lines (prefer smaller)
- Maximum method size should be 75 lines (prefer smaller)
-
Package Structure:
io.bayat.project.feature
as the base package pattern- Feature packages should be organized by domain concepts
- Utility classes in a
util
package - Constants in a
constants
package - Exceptions in an
exception
package
- Default to Java 17 LTS for new projects
- Consider Java 21 (or latest LTS) for projects specifically needing newer features
- Maintain backward compatibility as required by the project
-
Java 8+ Features:
- Prefer lambda expressions for functional interfaces
- Use Stream API for collection operations where appropriate
- Use Optional to represent absent values (not for performance-critical code)
- Use method references instead of lambdas where possible
- Utilize default methods in interfaces when applicable
-
Java 9+ Features:
- Use the module system for large applications
- Utilize factory methods for collections (
List.of()
,Map.of()
, etc.) - Use try-with-resources for all AutoCloseable resources
-
Java 10+ Features:
- Use
var
for local variables when the type is obvious - Avoid
var
when it reduces readability or type clarity
- Use
-
Java 14+ Features:
- Use pattern matching for instanceof where applicable
- Use records for simple data carriers
- Use switch expressions for multi-way conditionals
- Avoid raw types (use generics)
- Minimize use of checked exceptions for control flow
- Avoid unnecessary object creation
- Don't use
null
to represent optional values or absence - Avoid finalizers and object.finalize()
- Avoid excessive inheritance hierarchies (prefer composition)
- Don't use
public
fields (use accessor methods)
-
Creational Patterns:
- Builder Pattern for complex object construction
- Factory Method for object creation logic
- Dependency Injection for service components
-
Structural Patterns:
- Adapter for interface compatibility
- Decorator for adding behavior dynamically
- Composite for tree structures
-
Behavioral Patterns:
- Strategy for encapsulating algorithms
- Observer for event handling
- Command for action encapsulation
- Use constructor injection as the primary DI approach
- Field injection should be avoided except in tests
- Use Spring Framework annotations consistently
-
Exception Types:
- Use unchecked exceptions (runtime) for programming errors
- Use checked exceptions only when the caller should handle the exception
- Create custom exception hierarchies for the application domain
-
Exception Handling:
- Always include a cause when wrapping exceptions
- Use specific catch blocks before general ones
- Log exceptions appropriately before handling/rethrowing
- Clean up resources in finally blocks or try-with-resources
-
Logging:
- Use SLF4J API for logging
- Include context information in log messages
- Use appropriate log levels (ERROR, WARN, INFO, DEBUG, TRACE)
- Don't log sensitive information
-
Immutability:
- Make classes immutable when possible
- Use final fields for immutable objects
- Ensure proper visibility with volatile or atomic variables
-
Synchronization:
- Prefer higher-level concurrency utilities over
synchronized
keyword - Use
java.util.concurrent
package classes - Avoid blocking operations in critical sections
- Document thread-safety characteristics
- Prefer higher-level concurrency utilities over
-
Executors and Thread Pools:
- Use ExecutorService instead of raw threads
- Size thread pools appropriately for the workload
- Shut down executors properly
- Handle rejected executions gracefully
-
Testing Framework:
- Use JUnit 5 for unit tests
- Use Mockito for mocking dependencies
- Use AssertJ for fluent assertions
-
Test Structure:
- Follow the AAA pattern (Arrange, Act, Assert)
- One concept per test
- Use descriptive test names
- Aim for test independence
-
Coverage Requirements:
- Minimum 80% code coverage for business logic
- Test both positive and negative cases
- Test boundary conditions
- Test exception paths
- Use Spring Boot Test for integration tests
- Use TestContainers for external dependencies
- Clean up test resources after tests
- Avoid testing the same logic in both unit and integration tests
-
Javadoc:
- All public APIs must have Javadoc comments
- Document parameters, returns, exceptions thrown
- Include example usage when appropriate
- Keep comments updated when code changes
-
Comments:
- Comment complex algorithms and business logic
- Avoid obvious comments that repeat the code
- Use TODO comments for future improvements (with ticket reference)
- Document API contracts and invariants
-
Project Structure:
- Follow standard Maven directory structure
- Use Maven wrapper for consistent builds
- Organize multi-module projects appropriately
-
Dependency Management:
- Use Maven BOM (Bill of Materials) for version management
- Specify dependency versions explicitly
- Minimize transitive dependencies
- Use appropriate dependency scopes
-
Build Configuration:
- Configure compilation for appropriate Java version
- Use standardized plugins for common tasks
- Externalize configuration from pom.xml where appropriate
- Use Gradle Kotlin DSL for build scripts
- Follow conventions for directory structure
- Use version catalogs for dependency management
- Apply appropriate Gradle plugins for quality checks
-
Spring Boot:
- Use Spring Boot for new applications
- Follow Spring Boot conventions and defaults
- Use Spring Initializr for project setup
- Use starter dependencies when available
-
Spring Components:
- Use appropriate stereotypes (@Component, @Service, @Repository)
- Favor constructor injection
- Use Spring profiles for environment-specific configuration
- Externalize configuration using @ConfigurationProperties
-
JPA/Hibernate:
- Follow JPA entity design best practices
- Use appropriate fetch strategies
- Map relationships correctly
- Use query methods or JPQL for simple queries
-
Spring Data:
- Use Spring Data repositories
- Apply appropriate query methods
- Use specifications for complex queries
- Configure auditing for entity tracking
-
Tools:
- Use SonarQube for code quality analysis
- Configure SpotBugs for bug detection
- Use Checkstyle for style enforcement
- Apply PMD for common programming flaws detection
-
Quality Gates:
- No critical or blocker issues
- Maintain or improve technical debt ratio
- Maintain minimum test coverage
- Code duplication under 5%
-
Optimization:
- Optimize only after profiling
- Consider memory usage and garbage collection
- Use appropriate collection implementations
- Cache expensive computations
-
Benchmarking:
- Use JMH for micro-benchmarks
- Document performance characteristics
- Test with realistic data volumes
- Consider performance during code reviews
- Google Java Style Guide
- Effective Java by Joshua Bloch
- Spring Framework Documentation
- Oracle Java Coding Guidelines
Version | Date | Description |
---|---|---|
1.0 | 2025-03-20 | Initial version |