3.4. Code Writing Rules
3.4.1. Access Modifiers
- Class fields must default to
private. - Provide
publicmethods only when external access is required. - Classes used only within the package must be declared as package-private (omit the access modifier).
3.4.2. Import Rules
- Wildcard imports (
import java.util.*) must not be used. - Unused imports must be removed.
- Google Java Format handles import ordering automatically.
3.4.3. No Magic Numbers
Literal values must not be used directly in code. Define them as constants to clarify their meaning.
java
// Bad
if (retryCount > 3) { ... }
// Good
private static final int MAX_RETRY_COUNT = 3;
if (retryCount > MAX_RETRY_COUNT) { ... }3.4.4. Optional Usage Rules
- Use
Optionalas a return type. Do not use it for fields or parameters. - Do not call
Optional.get()directly. UseorElseThrow(),orElse(), orifPresent()instead.
java
// Bad
UsersRecord record = userRepository.findById(id).get();
// Good
UsersRecord record = userRepository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));3.4.5. Null Handling
- Do not return
null. Use empty collections (Collections.emptyList()) orOptionalinstead. - Use
Objects.requireNonNull()for null checks on parameters. - Actively use
@Nullableand@NonNullannotations.
3.4.6. String Handling
- Use
String.format()or text blocks (""") instead of the+operator for string concatenation. - Use
String.isEmpty()orString.isBlank()for empty string comparison.