Java Programming Best Practices and Conventions
Avoid Auto-boxing/Unboxing Operations
Bad Practice: This approach can lead to hard-to-trace NPEs
// Anti-pattern
public static int process(Integer value) {
return value; // Potential NPE during unboxing
}
Good Practice: Maintain consistent parameter types
// Recommended approach
public static Integer process(Integer value) {
return value; // No unboxing occurs
}
Thread Safety with Date Formatting
SimpleDateFormat is not thread-safe. Avoid static instances unless properly synchronized.
Bad Practice: Unsafe static usage
private static final SimpleDateFormat dateFormatter =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Good Practice: Thread-safe alternatives
private static final ThreadLocal<SimpleDateFormat> threadSafeFormatter =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
String Comparison
Bad Practice: Potential NPE
object.equals("test"); // Unsafe if object is null
Good Practice: Null-safe comparison
"test".equals(object); // Null-safe
// Or using Objects.equals()
Objects.equals(object1, object2);
Transaction Management
Ensure proper exception handling in transactional contexts
Bad Practice: Silent exception swallowing
@Transactional
public void save(User user) {
try {
// DB operations
} catch(Exception e) {
// Exception silently swallowed
}
}
Good Practice: Proper exception propagation
@Transactional
public void save(User user) {
try {
// DB operations
} catch(Exception e) {
throw e; // Ensure rollback
}
}
Finally Block Pitfalls
Bad Practice: Return in finally block overrides try block
public static boolean validate(String input) {
try {
return input.equals("123");
} finally {
return true; // Always returns true
}
}
Good Practice: Clean return statement
public static boolean validate(String input) {
return "123".equals(input);
}
Logging Practices
- Use SLF4J as logging facade rather then direct logging framework APIs
- Maintain logs for at least 15 days (minimum)
- Retain security-related logs for at least 6 months