Input validation is a critical process of ensuring that user-provided or external data meets specific criteria before processing. In Java, multiple methods can be used to validate method inputs effectively.
Validation Techniques
graph TD
A[Input Validation Techniques]
A --> B[Assertions]
A --> C[Explicit Checks]
A --> D[Java Bean Validation]
A --> E[Custom Validation Methods]
1. Explicit Null and Range Checks
public void processUserData(String username, int age) {
if (username == null || username.isEmpty()) {
throw new IllegalArgumentException("Username cannot be null or empty");
}
if (age < 0 || age > 120) {
throw new IllegalArgumentException("Invalid age range");
}
}
2. Assertion-Based Validation
public void calculateSalary(double hours, double hourlyRate) {
assert hours >= 0 : "Hours cannot be negative";
assert hourlyRate > 0 : "Hourly rate must be positive";
double salary = hours * hourlyRate;
}
Validation Method Comparison
Method |
Pros |
Cons |
Use Case |
Explicit Checks |
Clear, Immediate |
Verbose |
Production Code |
Assertions |
Lightweight |
Disabled in Production |
Development/Testing |
Bean Validation |
Standardized |
Requires Additional Dependency |
Complex Objects |
Advanced Validation Techniques
3. Regular Expression Validation
public void validateEmail(String email) {
String emailRegex = "^[A-Za-z0-9+_.-]+@(.+)$";
assert email.matches(emailRegex) : "Invalid email format";
}
4. Custom Validation Methods
public class UserValidator {
public static void validate(User user) {
assert user != null : "User cannot be null";
assert isValidUsername(user.getUsername()) : "Invalid username";
assert isValidAge(user.getAge()) : "Invalid age";
}
private static boolean isValidUsername(String username) {
return username != null && username.length() >= 3;
}
private static boolean isValidAge(int age) {
return age > 0 && age < 120;
}
}
Validation Frameworks
Java Bean Validation (JSR 380)
public class User {
@NotNull(message = "Username cannot be null")
@Size(min = 3, max = 50)
private String username;
@Min(value = 18, message = "Minimum age is 18")
@Max(value = 120, message = "Maximum age is 120")
private int age;
}
- Validation adds computational overhead
- Use lightweight methods
- Disable assertions in production environments
- Consider using dedicated validation frameworks for complex scenarios
Best Practices
- Validate inputs as early as possible
- Use clear, descriptive error messages
- Choose appropriate validation technique
- Balance between robustness and performance
By mastering these input validation methods, developers can create more reliable and secure applications in their LabEx Java projects.