Practical Usage Patterns
Configuration Management
public class DatabaseConfig {
public static final String DB_HOST = "localhost";
public static final int DB_PORT = 5432;
public static final String DB_USERNAME = "labex_user";
public static final int MAX_POOL_SIZE = 10;
}
Error Codes and Messages
public class ErrorConstants {
public static final int SUCCESS = 0;
public static final int ERROR_NETWORK = 100;
public static final int ERROR_AUTH = 200;
public static final String MSG_SUCCESS = "Operation completed successfully";
public static final String MSG_NETWORK_ERROR = "Network connection failed";
}
Validation Constraints
public class ValidationConstants {
public static final int MIN_PASSWORD_LENGTH = 8;
public static final int MAX_USERNAME_LENGTH = 50;
public static final String EMAIL_REGEX =
"^[A-Za-z0-9+_.-]+@(.+)$";
}
Enum Usage Patterns
graph TD
A[Enum Constants] --> B[State Management]
A --> C[Type Safety]
A --> D[Predictable Behavior]
Practical Enum Example
public enum UserRole {
ADMIN(3, "Full Access"),
EDITOR(2, "Partial Access"),
VIEWER(1, "Read-Only");
private final int level;
private final String description;
UserRole(int level, String description) {
this.level = level;
this.description = description;
}
}
public class PerformanceConstants {
public static final int CACHE_EXPIRY_SECONDS = 3600;
public static final int MAX_RETRY_ATTEMPTS = 3;
public static final long THREAD_TIMEOUT_MS = 5000L;
}
Usage Patterns Comparison
Pattern |
Use Case |
Example |
Configuration |
System Settings |
Database Connection |
Error Handling |
Status Codes |
Network Error Codes |
Validation |
Input Constraints |
Password Rules |
Performance |
Optimization Limits |
Caching Parameters |
Advanced Constant Techniques
Conditional Constants
public class SystemConstants {
public static final boolean IS_PRODUCTION =
System.getenv("ENV").equals("PROD");
public static final String API_ENDPOINT =
IS_PRODUCTION ? "https://api.labex.io" : "http://localhost:8080";
}
Best Practices
- Use constants for repeated values
- Group related constants
- Prefer
enum
for fixed sets of values
- Keep constants close to their usage
Security Considerations
public class SecurityConstants {
public static final int MAX_LOGIN_ATTEMPTS = 5;
public static final long LOCKOUT_DURATION_MS =
TimeUnit.MINUTES.toMillis(30);
}
Internationalization Constants
public class LocalizationConstants {
public static final Locale DEFAULT_LOCALE = Locale.ENGLISH;
public static final String[] SUPPORTED_LANGUAGES = {
"en", "es", "fr", "de", "zh"
};
}
By implementing these practical usage patterns, developers can create more maintainable and robust Java applications with LabEx's comprehensive programming approach.