Java – Best Practices
- Prefer immutability — use
final fields wherever possible
- Use
Optional<T> for nullable return values — never return null from a public API
- Use streams and lambdas for collections — avoid nesting more than 2 levels
- Always override
hashCode() when you override equals()
- Close resources in try-with-resources blocks
- Always add
@Override on overridden methods
- Use
@Transactional at the service layer, not the controller layer
Optional Example
// Correct
public Optional<User> findUser(Long id) {
return userRepository.findById(id);
}
// Incorrect
public User findUser(Long id) {
return userRepository.findById(id).orElse(null);
}
Try-With-Resources Example
// Correct
try (Connection conn = dataSource.getConnection()) {
// use conn
}
// Incorrect
Connection conn = dataSource.getConnection();
// use conn — never closed if exception thrown