Java Development Guidelines
References: Google Java Style Guide, Alibaba Java Development Manual
Toolchain
# Maven
mvn clean compile # Compile
mvn test # Run tests
mvn verify # Run all checks
# Gradle
./gradlew build # Build
./gradlew test # Run tests
Naming Conventions
| Type |
Rule |
Example |
| Package Name |
All lowercase, reversed domain name |
com.example.project |
| Class Name |
UpperCamelCase, noun/noun phrase |
UserService, HttpClient |
| Method Name |
lowerCamelCase, starting with a verb |
findById, isValid |
| Constant |
UPPER_SNAKE_CASE |
MAX_RETRY_COUNT |
| Boolean Return |
Prefix with is/has/can |
isActive(), hasPermission() |
Class Member Ordering
public class Example {
// 1. Static constants
public static final String CONSTANT = "value";
// 2. Static variables
private static Logger logger = LoggerFactory.getLogger(Example.class);
// 3. Instance variables
private Long id;
// 4. Constructors
public Example() { }
// 5. Static methods
public static Example create() { return new Example(); }
// 6. Instance methods (public → private)
public void doSomething() { }
private void helperMethod() { }
// 7. Getters/setters (or use Lombok)
}
DTO/VO Class Guidelines
| Rule |
Description |
| ❌ Do not handwrite getters/setters |
Always use Lombok for DTO, VO, Request, and Response classes |
✅ Use @Data |
Regular DTOs |
✅ Use @Value |
Immutable DTOs |
✅ Use @Builder |
Use alongside annotations when there are many fields |
⚠️ Use @Data cautiously on Entity classes |
Lombok's equals/hashCode in JPA Entities affects Hibernate proxies |
// ❌ Handwritten getters/setters
public class UserDTO {
private Long id;
private String name;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
// ... Extensive boilerplate code
}
// ✅ Use Lombok
@Data
public class UserDTO {
private Long id;
private String name;
}
Batch Query Guidelines
| Rule |
Description |
| ❌ Do not exceed 500 parameters in IN clauses |
High SQL parsing overhead and unstable execution plans |
| ✅ Batch queries when exceeding limits |
Batch by 500 items and merge results |
| ✅ Encapsulate generic utility methods |
Avoid writing manual batching logic everywhere |
// ❌ Querying 1700 IDs at once
List<User> users = userRepository.findByIdIn(allIds); // IN clause is too long
// ✅ Batch query utility method
public static <T, R> List<R> batchQuery(List<T> params, int batchSize,
Function<List<T>, List<R>> queryFn) {
List<R> result = new ArrayList<>();
for (int i = 0; i < params.size(); i += batchSize) {
List<T> batch = params.subList(i, Math.min(i + batchSize, params.size()));
result.addAll(queryFn.apply(batch));
}
return result;
}
// Usage
List<User> users = batchQuery(allIds, 500, ids -> userRepository.findByIdIn(ids));
Preventing N+1 Queries
| Rule |
Description |
| ❌ Do not call Repository/Mapper inside loops |
Triggers a query on every iteration within stream/forEach/for |
| ✅ Query in batches outside the loop, convert results to Map |
Reduces query count from N to 1 (or count of distinct keys) |
// ❌ N+1: Querying count line-by-line inside a loop
records.forEach(record -> {
long count = deviceRepo.countByDeviceId(record.getDeviceId()); // Triggers a query per item
record.setDeviceCount(count);
});
// ✅ Batch query outside loop + Map lookup
List<String> deviceIds = records.stream()
.map(Record::getDeviceId).distinct().collect(Collectors.toList());
Map<String, Long> countMap = deviceRepo.countByDeviceIdIn(deviceIds).stream()
.collect(Collectors.toMap(CountDTO::getDeviceId, CountDTO::getCount));
records.forEach(r -> r.setDeviceCount(countMap.getOrDefault(r.getDeviceId(), 0L)));
Common N+1 scenarios and fix patterns:
| Scenario |
Inside loop (❌) |
Outside loop (✅) |
| count |
repo.countByXxx(id) |
repo.countByXxxIn(ids) → Map<id, count> |
| findById |
repo.findById(id) |
repo.findByIdIn(ids) → Map<id, entity> |
| exists |
repo.existsByXxx(id) |
repo.findXxxIn(ids) → Set<id> + set.contains() |
Concurrency Safety Guidelines
| Rule |
Description |
| ❌ Do not use read-modify-write |
Reading balance first then writing back causes lost updates under concurrency |
| ❌ Do not use check-then-act without fallback |
Checking first then acting invalidates conditions under concurrency |
| ✅ Use atomic update SQL |
UPDATE SET balance = balance + :delta WHERE id = :id |
| ✅ Or use optimistic locking |
@Version field + retry mechanism |
| ✅ Unique index fallback |
Last line of defense against duplicate insertions |
// ❌ read-modify-write race condition
PointsAccount account = accountRepo.findById(id);
account.setBalance(account.getBalance() + points); // Lost update during concurrency
accountRepo.save(account);
// ✅ Option 1: Atomic update SQL
@Modifying
@Query("UPDATE PointsAccount SET balance = balance + :points WHERE id = :id")
int addBalance(@Param("id") Long id, @Param("points") int points);
// ✅ Option 2: Optimistic locking
@Version
private Long version; // Add version field in Entity
// ❌ check-then-act without fallback (may cause duplicate settlements under concurrency)
if (!rewardRepo.existsByTenantIdAndPeriod(tenantId, period)) {
rewardRepo.save(new RankingReward(...));
}
// ✅ Unique index fallback + exception handling
// DDL: UNIQUE INDEX uk_tenant_period (tenant_id, ranking_type, period, rank_position)
try {
rewardRepo.save(new RankingReward(...));
} catch (DataIntegrityViolationException e) {
log.warn("Duplicate settlement intercepted by unique index: tenantId={}, period={}", tenantId, period);
}
Exception Handling
// ✅ Good: Catch specific exceptions and add context
try {
user = userRepository.findById(id);
} catch (DataAccessException e) {
throw new ServiceException("Failed to find user: " + id, e);
}
// ✅ Good: Auto-close resources
try (InputStream is = new FileInputStream(file)) {
// Use resource
}
// ❌ Bad: Catching overly broad exceptions
catch (Exception e) { e.printStackTrace(); }
Null Handling
// ✅ Use Optional
public Optional<User> findById(Long id) {
return userRepository.findById(id);
}
// ✅ Parameter validation
public void updateUser(User user) {
Objects.requireNonNull(user, "user must not be null");
}
// ✅ Safe null handling
String name = Optional.ofNullable(user)
.map(User::getName)
.orElse("Unknown");
Concurrent Programming
// ✅ Use ExecutorService
ExecutorService executor = Executors.newFixedThreadPool(10);
Future<Result> future = executor.submit(() -> doWork());
// ✅ Use CompletableFuture
CompletableFuture<User> future = CompletableFuture
.supplyAsync(() -> findUser(id))
.thenApply(user -> enrichUser(user));
// ❌ Bad: Creating threads directly
new Thread(() -> doWork()).start();
Testing Guidelines (JUnit 5)
class UserServiceTest {
@Test
@DisplayName("Find user by ID - returns user when user exists")
void findById_whenUserExists_returnsUser() {
// given
when(userRepository.findById(1L)).thenReturn(Optional.of(expected));
// when
Optional<User> result = userService.findById(1L);
// then
assertThat(result).isPresent();
assertThat(result.get().getName()).isEqualTo("test");
}
}
Spring Boot Guidelines
// ✅ Constructor injection
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final EmailService emailService;
}
// ✅ REST Controller
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public ResponseEntity<UserDto> findById(@PathVariable Long id) {
return userService.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
}
Auth Filter Fallback Principle
| Rule |
Description |
| ✅ optional-auth paths fallback to anonymous access when encountering invalid/expired/incomplete tokens |
Should not return 401/403 |
| ❌ Do not allow users with partial credentials to have a worse user experience than anonymous users |
e.g., temporary tokens returning 403 on public endpoints |
Preventing Circular Dependencies (Spring Boot 3.x)
Spring Boot 3.x disables constructor circular dependencies by default. When splitting sub-services from large Services, you must verify dependency flow direction.
| Approach |
Priority |
Suitable Scenario |
| Extract common methods to independent utility classes |
✅ Preferred |
Pure utility methods (e.g., resolveTenantIds) |
@Lazy field injection |
⚠️ Emergency |
Bidirectional calls are strictly required |
Function<> callbacks |
⚠️ Alternative |
Flexible but increases complexity |
// ❌ Sub-service calling parent service after refactoring → Circular dependency
@RequiredArgsConstructor
public class ReportInvoiceService {
private final ReportService reportService; // Application startup fails!
}
// ✅ Extract common methods into a separate class
@Component
public class TenantHelper {
public List<Long> resolveTenantIds(Long tenantId) { ... }
}
See refactor-safety skill - Pitfall #5 for details
Pagination Parameter Guidelines (Spring Data JPA)
Spring Data JPA pagination indices are 0-based. When refactoring pagination parameters, ensure frontend and backend index baselines match.
| Rule |
Description |
| Full-stack unified 0-based |
Frontend, Controller, Service, and JPA all use 0-based indexing |
| Controller default value must be 0 |
@RequestParam(defaultValue = "0") int page |
| Service uses page directly |
PageRequest.of(page, size), do not use page - 1 |
// ❌ Incorrect: Frontend passes page=0, Controller defaults to 1, Service subtracts 1
@GetMapping("/list")
public Page<Product> list(@RequestParam(defaultValue = "1") int page) {
return service.list(page); // Inside Service: PageRequest.of(page - 1, size)
}
// Issue: Frontend passes page=0 → Service calculates page - 1 = -1 → Exception
// ✅ Correct: Full-stack unified 0-based
@GetMapping("/list")
public Page<Product> list(@RequestParam(defaultValue = "0") int page) {
return service.list(page); // Inside Service: PageRequest.of(page, size)
}
Refactoring Checklist:
- [ ] Frontend calls pass
page: 0 (1st page)
- [ ] Controller default value is
0
- [ ] Service uses
PageRequest.of(page, size) (without subtracting 1)
- [ ] Verify both
page=0 and page=1 return data normally in tests
Input Validation Guidelines
| Rule |
Description |
❌ Do not use @RequestBody without @Valid |
Every request body must be validated |
| ✅ Add constraint annotations to DTO fields |
@NotBlank, @Size, @Pattern, etc. |
| ✅ Add range constraints to numeric fields |
@Min, @Max, @Positive, etc. |
| ✅ Set upper bounds for pagination parameters |
size must have @Max(100) to prevent massive queries |
| ✅ Whitelist validation for enum/status fields |
Custom validator or @Pattern |
Common DTO Field Validation Quick Reference:
| Field Type |
Required Annotation |
Description |
| Quantity |
@NotNull @Min(1) |
Prevents 0 or negative numbers (negatives can trigger inverse operations) |
| Amount amount/price |
@NotNull @Positive |
Or @DecimalMin("0.01") |
| Pagination size |
@Min(1) @Max(100) |
Prevents size=999999 from overwhelming the database |
| Pagination page |
@Min(1) |
Page numbers start from 1 |
| Percentage rate |
@Min(0) @Max(100) |
Range depends on business rules |
// ❌ Unvalidated; arbitrary input enters business logic directly
@PostMapping("/ship")
public Result ship(@RequestBody ShippingRequest request) { ... }
// ✅ Fully validated
@PostMapping("/ship")
public Result ship(@RequestBody @Valid ShippingRequest request) { ... }
public record ShippingRequest(
@NotNull Long orderId,
@NotBlank @Size(max = 500) String shippingInfo,
@Pattern(regexp = "pending|shipped|delivered") String giftStatus
) {}
// ❌ quantity only has @NotNull; negative numbers allow Redis DECRBY to increment stock inversely
public record CreateOrderRequest(
@NotNull Integer quantity // Allows submitting 0 or negative numbers
) {}
// ✅ quantity must be >= 1
public record CreateOrderRequest(
@NotNull @Min(1) Integer quantity
) {}
// ❌ Uncapped pagination; users can pass size=999999
@GetMapping("/orders")
public Result list(@RequestParam int page, @RequestParam int size) { ... }
// ✅ Pagination parameters constrained
@GetMapping("/orders")
public Result list(@RequestParam @Min(1) int page,
@RequestParam @Min(1) @Max(100) int size) { ... }
Performance Optimization
| Pitfall |
Solution |
| N+1 queries |
See "Preventing N+1 Queries" section |
| String concatenation inside loops |
Use StringBuilder |
| Frequent boxing and unboxing |
Use primitive streams |
| Unspecified initial collection capacity |
new ArrayList<>(size) |
Third-Party API HTTP Client Selection
| Rule |
Description |
❌ Avoid using RestTemplate default client for domestic platform APIs |
Default HttpURLConnection POST requests have compatibility issues with CDNs like WeChat/Alipay (known to trigger 412/403) |
✅ Prefer java.net.http.HttpClient (JDK 11+) |
Modern HTTP client without CDN compatibility issues |
✅ Or configure HttpComponentsClientHttpRequestFactory |
Configures RestTemplate to use Apache HttpClient under the hood |
Diagnostic Characteristics: HTTP error + empty body + minimal response headers (only Connection/Content-Length) = CDN-level interception, not a response from the API itself. When GET requests succeed but POST requests fail on the same API, suspect HTTP client compatibility first.
Native SQL Guidelines
Avoid MySQL Reserved Words in Aliases
Using MySQL reserved words as column aliases in @Query(nativeQuery = true) causes syntax errors.
High-frequency Reserved Words: year_month, order, status, key, value, name, type, date, time, rank, range, rows, column, user, role, group
| Rule |
Description |
| ✅ Use short aliases or abbreviations |
ym, ord_status, cnt |
| ✅ Or escape with backticks |
`year_month` |
| ❌ Do not use reserved words directly as aliases |
as year_month, as order, as rank |
// ❌ year_month is a MySQL reserved word (INTERVAL YEAR_MONTH)
@Query(value = """
SELECT DATE_FORMAT(o.order_date, '%Y-%m') as year_month,
COUNT(*) as cnt
FROM orders o
GROUP BY year_month
""", nativeQuery = true)
// ✅ Use non-reserved word alias instead
@Query(value = """
SELECT DATE_FORMAT(o.order_date, '%Y-%m') as ym,
COUNT(*) as cnt
FROM orders o
GROUP BY ym
""", nativeQuery = true)
Logging Guidelines
// ✅ Parameterized logging
log.debug("Finding user by id: {}", userId);
log.info("User {} logged in successfully", username);
log.error("Failed to process order {}", orderId, exception);
// ❌ Bad: String concatenation
log.debug("Finding user by id: " + userId);
Detailed References
| File |
Content |
references/java-style.md |
Naming conventions, exception handling, Spring Boot, testing standards |
references/collections.md |
Immutable collections (Guava), string splitting |
references/concurrency.md |
Thread pool configuration, CompletableFuture timeouts |
references/concurrency-db-patterns.md |
Get-Or-Create concurrency, N+1 prevention, atomic updates, Redis+DB consistency |
references/code-patterns.md |
Guard clauses, enum optimization, strategy factory patterns |
references/date-time.md |
Date arithmetic, accounting period calculations, avoiding month-end alignment |
references/http-client.md |
Third-party API HTTP client selection, CDN compatibility issues |
📋 This response follows: java-dev - [Specific Section]